Python List index & count method with Example – Python Tutorial

1 year ago Lalit Bhagtani 0

In this tutorial, we will learn about python list index and count method.
Python List Index

index method :

List index method is used to get the index of first occurrence of item ( passed as an argument ) in a list object. Here start is a start index and end is a end index, if values of start and end are passed as an argument then first occurrence of item is searched between these two indexes.

Syntax : < List Object >.index( < item > [ , start [ ,  end ] ] ) : < int >

Example:

[datacamp_exercise lang=”python” height=”450″ min-height=”200″ max-height=”500″]
[datacamp_pre_exercise_code]

[/datacamp_pre_exercise_code]
[datacamp_sample_code]
# Python List index example
# create list object and assign it to variable l
l = [‘a’,’b’,’c’,’d’,’e’,’b’,’c’]

# calling index() method by passing ‘b’ as an argument
index = l.index(‘b’)

# print the value of variable index
print(index)

# calling index() method by passing ‘b’ and starting index 2
index = l.index(‘b’,2)

# print the value of variable index
print(index)

# calling index() method by passing ‘b’, 0 as starting index and 2 as ending index
index = l.index(‘b’,0,2)

# print the value of variable index
print(index)
[/datacamp_sample_code]
[datacamp_solution]

[/datacamp_solution]
[/datacamp_exercise]

count method :

This method is used to count total number of occurrence of item ( passed as an argument ) in a list object.

Syntax : < List Object >.count( < item > ) : < int >

Example:

[datacamp_exercise lang=”python” height=”250″ min-height=”200″ max-height=”400″]
[datacamp_pre_exercise_code]

[/datacamp_pre_exercise_code]
[datacamp_sample_code]
# Python List count example
# create tuple object and assign it to variable l
l = [‘a’,’b’,’c’,’d’,’e’,’a’]

# calling count() method by passing ‘a’ as an argument
count = l.count(‘a’)

# print the value of variable count
print(count)
[/datacamp_sample_code]
[datacamp_solution]

[/datacamp_solution]
[/datacamp_exercise]

References :-

  1. index & count method Docs

That’s all for Python List index & count method. If you liked it, please share your thoughts in comments section and share it with others too.

Previous