Access Multiple List Elements by Index in Python (Example)
In this article, I’ll explain how to access multiple list elements by index in the Python programming language.
The post contains these topics:
If you would like to know more about these topics, keep reading.
The first step is to create some example data.
sample_list = [5, 8, 10, 12, 14, 16] # creating a sample list
The list we’ll use for the following example is called sample_list and contains six different integer values.
Example: Access Multiple List Elements by List Comprehension
To access multiple elements by indices, first, a list containing the indices to extract should be created.
This list is then used in a list comprehension. A list comprehension is a compact way of generating lists, for further details you can check out the list comprehension documentation.
An example of the application is shown below.
indices = [1,3,5] # creating a list of indices print([sample_list[index] for index in indices]) # printing the result list # [8, 12, 16]
In our example, we have selected the index positions 1, 3, and 5. This resulted in a subset of our list that contains the values 8, 12, and 16.
Video, Further Resources & Summary
Have a look at the following video on my YouTube channel. In the video, I’m explaining the contents of this post.
The YouTube video will be added soon.
In addition, you may have a look at the other articles on my website:
- Access Index of List in Python
- Access List Index in for Loop in Python
- Convert pandas DataFrame Index to List & NumPy Array in Python
- Access Index of Last Element in pandas DataFrame in Python
- Python Programming Tutorials
In this Python tutorial, you have learned how to create a child list of elements from a list. If you have further questions on how to extract and print certain items from a list, tell me about them in the comments section.
This page was created in collaboration with Ömer Ekiz. Have a look at Ömer’s author page to get more information about his professional background, a list of all his tutorials, as well as an overview of his other tasks on Statistics Globe.