Python get element from list by index

In this short tutorial, learn to find the index of an element in a list in Python. We look at the code to achieve this with its pros and cons.

Before we delve into how you could find the index of an element in a list, we do a small recap on what lists are, in Python. However, in case you are already familiar with it, you can head straight to the Solution.

Table of Contents - Find index of element in list Python

  • Lists in Python - Recap
  • Find index of element in list Python
  • Code and Explanation
  • Limitations and Caveats
  • Other Related Concepts

List in Python - Recap

Lists in Python are an ordered collection of items and these items could be of various data types. Lists are enclosed in square brackets [[ ]] and the items in a list are separated by commas. Given lists are an ordered collection of items, each element has its unique position, and each element can be accessed by telling Python the position. These positions are called indexes. Index in a list starts with 0. This essentially means that the first element in the list has an index of 0 and not 1 and subsequently the second element has an index of 1. This concept holds true for most programming languages. If you have trouble understanding this concept at first, just keep in mind that the indexes are all off-by-one.

With that out of the way let us look at how to find the index of an element in list Python.

Find index of element in list in Python:

Since the index of lists is used to access elements in Python, it is only natural that one would want to find the index of an element. This may seem easy when dealing with a small list; however, this could become tedious when the length of the list increases. To facilitate this, Python has an inbuilt function called index[]. This function takes in the element as an argument and returns the index. By using this function we are able to find the index of an element in a list in Python.

Syntax of Index[]::

list.index[element, start, end] Here, “list” refers to the name of the list you are looking to search.

Parameters:

  • Element - Required, the element whose index you would like to find.
  • Start - Optional, the index to start the search.
  • End - Optional, the index to end the search.

Return Values:

  • Return the index of the passed element
  • ValueError is returned if the element is not found

Code and Explanation:

data_types = ["Str", "Int", "Float"] # Searching for “int” print[data_types.index["Int"]] #Output - 1 As you can see, we have used the above code to find the index of an element in a list. Next, let us look at an example using the other two parameters.vowels = ['a', 'e', 'i', 'o', 'i', 'u'] # Searching for “o” within index 1-5 print[vowels.index["o",1,5]] #Output - 3 # Searching for “o” within index 1-3 print[vowels.index["o",0,2]] #Output - ValueError: 'o' is not in list In the above code, we first search for the element “o” between the 1st and 5th index, and the index is returned as the element is present. However, the second code snippet searches for “o” between the 0th and 2nd index, and since “o” is at the 3rd index a ValueError is returned as “o” couldn’t be found.

This is how you used the index[] function to find the index of an element in a list.

Find index of element in list Python - Limitations and Caveats:

  • ValueErrors are returned if the element cannot be found, I would recommend using a try-catch in case you are using it in a bigger piece of code.
  • The parameters are case-sensitive and index[] would return a ValueError even if the element is present but in a different case. I would recommend using the .upper or .lower methods in case you aren’t sure about the case.
  • Index[] method only returns the index of the first occurrence, in case you are looking for the subsiding occurrence using the start and stop parameter accordingly.
  • P.S. If you’d like to learn more about lists, check out these tutorials on checking if a list is empty and removing items from lists.

We continue with Flexiple's tutorial series to explain the code and concept behind common use cases. In this article ...

We continue with Flexiple's tutorial series to explain the code and concept behind common use cases. In this article ... 

Python list is an essential container as it stores elements of all the datatypes as a collection. Knowledge of certain list operations is necessary for day-day programming.

Python find in list

To find an element in the Python list, use one of the following approaches.

  1. Find an element in the list by index in Python.
  2. Python Linear search on the list. 

Find Element In List By Index In Python

To find an element in the list, use the Python list index[] method, The index[] method searches an item in the list and returns its index. Python index[] method finds the given element in the list and returns its position.

If the same element is present more than once, the method returns the index of the first occurrence of the element.

The index in Python starts from 0, not 1.

So through an index, we can find the position of an element in the list.

See the following code example.

# app.py streaming = ['netflix', 'hulu', 'disney+', 'appletv+'] index = streaming.index['disney+'] print['The index of disney+ is:', index]

Output

➜ pyt python3 app.py The index of disney+ is: 2 ➜ pyt

The index[] method takes a single argument, which is the element, and it returns its position in the list.

Python search on the list

It is the straightforward approach is to do a linear search; for example,

  1. Start from the leftmost item of the list and one by one compare x with each item of the list.
  2. If x matches with an item, return True.
  3. If x doesn’t match with any of the items, return False.

See the following code.

# app.py def search[list, platform]: for i in range[len[list]]: if list[i] == platform: return True return False streaming = ['netflix', 'hulu', 'disney+', 'appletv+'] platform = 'netflix' if search[streaming, platform]: print["Platform is found"] else: print["Platform does not found"]

In the above code, we have first created a user-defined function called a search that accepts two arguments.

The first argument is our list in which we need to find the item, and the second parameter is the platform, which is the string we need to search in the list.

So, we are looping through a list and compare each element of the list to the platform argument.

If both are matched, then the element is found; otherwise, it is not.

Output

➜ pyt python3 app.py Platform is found ➜ pyt

Check if the item exists in the list using the “in” operator

To check if an element exists in the list, use Python in operator.

Syntax

element in list

It will return True if an element exists in the list; else return False.

See the following code.

# app.py streaming = ['netflix', 'hulu', 'disney+', 'appletv+'] platform = 'hulu' if platform in streaming: print['Hulu is in the streaming service business'] else: print['It does not include']

Output

➜ pyt python3 app.py Hulu is in the streaming service business ➜ pyt

Filtering a collection in Python

To find all elements in a sequence that meet a specific condition, use the list comprehension or generator expressions.

See the following code example.

# app.py streaming = ['netflix', 'hulu', 'disney+', 'appletv+'] platform = 'hulu' result = any[len[elem] == 8 for elem in streaming] if result: print["Yes, string with length 8 is found"] else: print['Not found']

In the above code, we are searching for an element whose string length is 8. If found, it will print “Yes, string with length 8 is found” otherwise not found.

Output

➜ pyt python3 app.py Yes, string with length 8 is found ➜ pyt

Conclusion

Python list can contain different data types like integer, string, boolean, etc. Sometimes, it requires to search particular elements in the list. The items can be searched in the python list in various ways. We have seen the ways like search element in the list by index, linear search on the list,

That is it for the Python find in list example.

Related Posts

How to Access Characters in String by Index in Python

How to Convert Python List to JSON

How to Convert Python Dictionary to String

How to Convert Python List to Dictionary

How to Convert Python String to List and List to String

Video liên quan

Chủ Đề