Python List - Access Items - list[index], list[range]


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

The following is a quick code snippet to access an item or sublist from a given list my_list.

# Access item at index=5
my_list[5]

# Access items in the range [2, 7)
my_list[2:7]

If you would like to iterate through all the items of the list, you can refer: loop list items.

Examples

1: Access a single item in given list using index

You can use square brackets next to the array variable name with the index in between the brackets.

In the following example, we tale a Python list in my_list, and then access 3rd item using index. since index starts from 0, the index of the 3rd item is 2.

Python Program

my_list = [52, 85, 'apple', 'banana']

# Access 3rd item whose index=2
item = my_list[2]

print(item)

Output

apple

my_list[2] returns element at index 2 in the list my_list.

2. Access a range of items in list using slicing

You can also get a sub-list or a range of items from the list by providing the range of index. This is called slicing in Python.

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

my_list = [52, 85, 41, 'apple', 'banana']

# Access a range of items
sub_list = my_list[1:4]

print(sub_list)

Output

[85, 41, 'apple']

Summary

In summary, 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.