Summary: in this tutorial, you’ll learn how to find the index of an element in a list.
To find the index of an element in a list, you use the index() function.
The following example defines a list of cities and uses the index() method to get the index of the element whose value is 'Mumbai':
cities = ['New York', 'Beijing', 'Cairo', 'Mumbai', 'Mexico'] result = cities.index('Mumbai') print(result)
Code language: Python (python)It returns 3 as expected.
However, if you attempt to find an element that doesn’t exist in the list using the index() function, you’ll get an error.
This example uses the index() function to find the Osaka city in the cities list:
cities = ['New York', 'Beijing', 'Cairo', 'Mumbai', 'Mexico'] result = cities.index('Osaka') print(result)
Code language: Python (python)Error:
ValueError: 'Osaka' is not in list
Code language: Python (python)To fix this issue, you need to use the in operator.
The in operator returns True if a value is in the list. Otherwise, it returns False.
Before using the index() function, you can use the in operator to check if the element that you want to find is in the list. For example:
cities = ['New York', 'Beijing', 'Cairo', 'Mumbai', 'Mexico'] city = 'Osaka' if city in cities: result = cities.index(city) print(f"The {city} has an index of {result}.") else: print(f"{city} doesn't exist in the list.")
Code language: Python (python)Output:
Osaka doesn't exist in the list.
Code language: Python (python)Summary
- Use the in operator with the index() function to find if an element is in a list.
Did you find this tutorial helpful ?
Python Lists and List Manipulation Video
Before starting, I should mention that the code in this blog post and in the video above is available on my github.
Defining a List
Lists are written within square brackets []
Defining a List. The second row in this table index is how you access items in the list.# Define a listz = [3, 7, 4, 2]
Lists store an ordered collection of items which can be of different types. The list defined above has items that are all of the same type (int), but all the items of a list do not need to be of the same type as you can see below.
heterogenousElements = [3, True, 'Michael', 2.0]
The list contains an int, a bool, a string, and a float.
Access Values in a List
Each item in a list has an assigned index value. It is important to note that python is a zero indexed based language. All this means is that the first item in the list is at index 0.
Access item at index 0 (in blue)# Define a listz = [3, 7, 4, 2]# Access the first item of a list at index 0
print(z[0])Output of accessing the item at index 0.
Python also supports negative indexing. Negative indexing starts from the end. It can be more convienient at times to use negative indexing to get the last item in the list because you don’t have to know the length of the list to access the last item.
Accessing the item at the last index.# print last item in the listprint(z[-1])Output of accessing the last item in the List
As a reminder, you could also access the same item using positive indexes (as seen below).
Alternative way of accessing the last item in the list zSlice of Lists
Slices are good for getting a subset of values in your list. For the example code below, it will return a list with the items from index 0 up to and not including index 2.
First index is inclusive (before the :) and last (after the :) is not# Define a listz = [3, 7, 4, 2]print(z[0:2])Slice of a list syntax. # everything up to but not including index 3
print(z[:3])
The code below returns a list with items from index 1 to the end of the list
# index 1 to end of listprint(z[1:])
Update Item in a List
Lists in Python are mutable. All that means is that after defining a list, it is possible to update the individual items in a list.
# Defining a listz = [3, 7, 4, 2]# Update the item at index 1 with the string "fish"
z[1] = "fish"
print(z)Code to modify an item in a list
List Methods
Python lists have different methods that help you modify a list. This section of the tutorial just goes over various python list methods.
Index Method
# Define a listz = [4, 1, 5, 4, 10, 4]
The index method returns the first index at which a value occurs. In the code below, it will return 0.
print(z.index(4))You can also specify where you start your search.
print(z.index(4, 3))Count Method
The count method works just like how it sounds. It counts the number of times a value occurs in a list
random_list.count(5)
Sort Method
Sort a Python List - the actual code would be: z.sort()The sort method sorts and alters the original list in place.
z = [3, 7, 4, 2]z.sort()
print(z)
The code above sorts a list from low to high. The code below shows that you can also sort a list from high to low.
Sort a python list from high to low# Sorting and Altering original list# high to low
z.sort(reverse = True)
print(z)
As an aside, I should mention that you can also sort a list of strings from a-z and z-a as you can see here.
Append Method
Add the value 3 to the end of the list.The append method adds an element to the end of a list. This happens inplace.
z = [7, 4, 3, 2]z.append(3)
print(z)
Remove Method
The remove method removes the first occurrence of a value in a list.
z = [7, 4, 3, 2, 3]z.remove(2)
print(z)Code removes the first occurrence of the value 2 from the list z
Pop Method
z.pop(1) removes the value at index 1 and returns the value 4.The pop method removes an item at the index you provide. This method will also return the item you removed from the list. If you don’t provide an index, it will by default remove the item at the last index.
z = [7, 4, 3, 3]print(z.pop(1))
print(z)
Extend Method
The method extends a list by appending items. The benefit of this is you can add lists together.
z = [7, 3, 3]z.extend([4,5])
print(z)Add the list [4, 5] to the end of the list z.
Alternatively, the same thing could be accomplished by using the + operator.
print([1,2] + [3,4])Insert Method
insert the list [1,2] at index 4The insert method inserts an item before the index you provide
z = [7, 3, 3, 4, 5]z.insert(4, [1, 2])
print(z)
Closing Remarks
Please let me know if you have any questions either here or in the comments section of the youtube video or through Twitter! Next post reviews python dictionaries. If you want to learn how to utilize the Pandas, Matplotlib, or Seaborn libraries, please consider taking my Python for Data Visualization LinkedIn Learning course. Here is a free preview video.