Last Updated on June 17, 2021 by Roshan Parihar
In this tutorial, learn how to get list element by index in Python. The short answer is: use the index operator ([]
) and pass the index value of the element as the argument. You can also get all the elements within range using the Python slice operator([:]
). Access the item of the list with the different methods given here.
You can get a single element or more than a single element within the range. By using the loop of Python, you can access all the elements of the list. You may also like to read how to loop over the Python list variable.
Get Single List Element By Index in Python
If you want to get the single element of the list in Python. You have to use the Python index operator which starts the element from zero(0). To get more items, you have to use the index again with the index value of the element.
1 2 |
myList = [5, "Six", 7, "Eight", 9, "Ten"]; print(myList[1]); |
Output
The above example showing the elements of the list that is at index 1. The example using the print statement to print the accessed element in the output.
However, the above example provides you only a single element. In order to get multiple elements, you have to use the Python slice operator([]
).
Access List Element Within Range in Python
The slice operator([]
) gives you all the elements within a certain range. The range requires two arguments to access an element within that range. The first argument is the starting index and the second argument is the end index value. However, you will get the value located to the previous index and not the end index value.
1 2 |
myList = [5, "Six", 7, "Eight", 9, "Ten"]; print(myList[0:4]); |
Output
The above example prints the four elements from the start of the list. You can change the range of the index as per your requirement.
How to Get All Element Using Python Loop
In addition to above all, you can access all the elements of the list using the for loop of Python. If you want to use the for loop of Python, you have to use the below-given example.
1 2 3 |
myList = [5, "Six", 7, "Eight", 9, "Ten"]; for a in myList: print(a); |
Output
Six
7
Eight
9
Ten
The above example showing all the list elements with a single element in a single line. Each element of the list gets printed one by one in the output.
DOWNLOAD Free PYTHON CHEAT SHEET
You may also like to read
- How to find the size of a list item using Python
- Concatenate two list variables in Python
- Create List Variable in Python
I hope you like this post on how to get a list element by index using Python.
References