HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

Python - Access List Items

In Python, you can access individual items in a list using indexing. Lists in Python are zero-indexed, meaning the index of the first element is 0, the second element is 1, and so on.

Creating a list

Example
my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']                 
             

Accessing individual items by index

Example
first_item = my_list[0]
second_item = my_list[1]
third_item = my_list[2]

print(first_item)  # Output: apple
print(second_item)  # Output: banana
print(third_item)  # Output: cherry
                
             

Negative indexing can be used to access elements from the end of the list

Example
last_item = my_list[-1]
second_to_last_item = my_list[-2]

print(last_item)  # Output: elderberry
print(second_to_last_item)  # Output: date                 
             

Slicing can be used to access a range of elements

Example
sliced_items = my_list[1:4]  # Elements from index 1 to 3 (exclusive)
print(sliced_items)  # Output: ['banana', 'cherry', 'date']                 
             

Omitting start or end index in slice defaults to start or end of list

Example
partial_list1= my_list[:3]  # Elements from the start up to index 2 
partial_list2 = my_list[2:]  # Elements from index 2 to the end

print(partial_list1)  # Output: ['apple', 'banana', 'cherry']
print(partial_list2)  # Output: ['cherry', 'date', 'elderberry']                 
             

Accessing elements with step

Example
step_list  = my_list[::2]  # Get every second element 
print(step_list)   # Output: ['apple', 'cherry', 'elderberry']