Python Access List Item (original) (raw)
Last Updated : 12 Dec, 2024
Whether we are working with numbers, strings or other data types, lists provide a versatile way to organize and manipulate data. But how to access specific items in a list? This article will guide you through various methods of accessing list items in Python.
Accessing List Items by Index
In Python, lists are indexed starting from 0. This means the first item in a list is at index 0, second item is at index 1 and so on. To access a list item, we simply specify the index in square brackets.
Python `
li = ['0', '1', '2']
print(li[0])
print(li[1])
print(li[2])
`
**Explanation:
- li[0] refers to the first item (0)
- li[1] refers to the second item (1)
- li[2] refers to the third item (2)
Let's take a look at other methods of accessing list items:
Table of Content
- Accessing List Items by Negative Index
- Using List Methods to Access Items
- Accessing List Items by Slicing Lists
- Accessing List Items Using Loops
Accessing List Items by Negative Index
Python allows negative indexing which enables us to access list items from the end. The last item in the list has an index of -1, the second-to-last item has an index of -2 and so on.
Python `
li = [1, 2, 3]
print(li[-1])
print(li[-2])
`
Negative indexing is especially useful when we want to retrieve items from the end of the list without knowing the exact length of the list.
Using List Methods to Access Items
Python provides various list methods to help us find or modify items. For example, index() helps us find the index of an item and pop() removes an item.
Python `
li = ['apple', 'banana', 'cherry']
print(li.index('banana'))
item = li.pop(1)
print(item)
print(li)
`
Output
1 banana ['apple', 'cherry']
The index() method returns the index of the first occurrence of the item while pop() removes an item at a specified index.
Accessing List Items by Slicing Lists
Slicing allows us to access a range of items from a list. We can specify a start index, an end index and an optional step.
Python `
li = ['apple', 'banana', 'cherry', 'date', 'elderberry']
print(li[1:4])
print(li[::2])
`
Output
['banana', 'cherry', 'date'] ['apple', 'cherry', 'elderberry']
In the first slice, li[1:4] gives elements from index 1 to 3 (not including 4). The second slice, li[::2], skips every other item.
Accessing List Items Using Loops
Here's a short example of accessing list items using a loop:
Python `
List of numbers
numbers = [10, 20, 30, 40, 50]
Using a for loop to access list items
for num in numbers: print(num)
`
In this example, the for loop iterates through each item in the numbers list and prints it.
For loop method follow article: Iterate over a list in Python.