Accessing List Items in Python
You can access the items of a list by referring to its index number. The indices start at 0
for the first element. Negative indices can be used to access elements from the end of the list.
Accessing Elements by Index
Example: Positive and Negative Indexing
# Accessing list items
fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry"]
first_fruit = fruits[0]
third_fruit = fruits[2]
last_fruit = fruits[-1]
second_last_fruit = fruits[-2]
print("First Fruit:", first_fruit)
print("Third Fruit:", third_fruit)
print("Last Fruit:", last_fruit)
print("Second Last Fruit:", second_last_fruit)
Output
First Fruit: Apple
Third Fruit: Cherry
Last Fruit: Elderberry
Second Last Fruit: Date
Explanation: Positive indices start from 0
and go up. Negative indices start from -1
(last item) and go down.
Slicing Lists
You can return a range of items by using the slicing syntax [start:stop]
, where start
is the index of the first item and stop
is the index where slicing stops (not included).
Example: List Slicing
# Slicing lists
sub_list1 = fruits[1:4]
sub_list2 = fruits[:3]
sub_list3 = fruits[2:]
print("Sub List 1:", sub_list1)
print("Sub List 2:", sub_list2)
print("Sub List 3:", sub_list3)
Output
Sub List 1: ['Banana', 'Cherry', 'Date']
Sub List 2: ['Apple', 'Banana', 'Cherry']
Sub List 3: ['Cherry', 'Date', 'Elderberry']
Explanation: Slicing allows you to get a subset of the list. Omitting start
defaults to 0
, and omitting stop
defaults to the length of the list.