In this tutorial, learn how to get list element by index in Python. You can also get all the elements within range using Python slide operator([:]). Access the item of the list with the different method 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 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 which is in the index 1. The example using the print statement to print the accessed element in the output.
However, the above example provides you only the 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 the 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 element with a single element in single line. Each element of the list gets printed one by one in the output.
You may also like to read
- How to find the size of list item using Python
- Concatenate two list variables in Python
- Create List Variable in Python
Hope, you like this post of how to get list element by index using Python. If you have any query regarding the tutorial, please comment below.
References
Also tell me, which method you are using to access list items by index and slice using Python.