Contents
Python List – Access Items
To access list items individually, you can use index just like an array. You can also access a range of items in the list by giving range as index.
In this tutorial, we shall go through some examples, to understand how to access items in a Python list.
Sample Code Snippet
Following is a quick code snippet to access an item or sublist from a given list.
mylist[5]
mylist[2:7]
Run If you would like to iterate through all the items of the list, you can refer: loop list items.
Example 1: Access a single item of Python List
You can use square brackets next to the array variable name with the index in between the brackets.
In the following example, we will create a Python list and then access 3rd item. Index of the 3rd item is 2, since index starts from 0.
Python Program
a = [52, 85, 41, 'sum', 'str', 3 + 5j, 6.8]
#access 3rd item with index 2
x = a[2]
print(x)
Run Output
41
a[2]
returns element at index 2
in the list a
.
Example 2: Access a range of items in Python List
You can also get a sub-list or a range of items from the list by providing the range of index.
In the following example, we will create a Python list and then access a range of items from 2nd item until 5th item, three items in total excluding the last index.
Python Program
a = [52, 85, 41, 'sum', 'str', 3 + 5j, 6.8]
#access a range of items
x = a[1:4]
print(x)
Run Output
[85, 41, 'sum']
Summary
To sum up this tutorial of Python Examples, we learned how to access one element of a list at an index, or a sublist using index range, with the help of well detailed example programs.
Related Tutorials
- Python – Traverse List except Last Element
- Python List of Lists
- How to Get List of all Files in Directory and Sub-directories?
- Python Program to Find Largest Number in a List
- Python – Count the items with a specific value in the List
- How to Reverse Python List?
- Python List without Last Element
- How to Get the list of all Python keywords?
- How to Sort Python List?
- Python – Check if Element is in List