Access List Items

You can access items in a list by referring to their index. In Python, lists are zero-indexed, meaning the first item has an index of 0.

Accessing Elements:

Python
fruits = ["apple", "banana", "cherry"]

# Access the first item
print(fruits[0])  # Output: apple

# Access the last item
print(fruits[-1])  # Output: cherry

In Python, you can access individual elements by specifying their index inside square brackets. Remember, the index starts from 0, so the first item is at index 0, the second at index 1, and so on. To access the last item, you can use a negative index.

Accessing a Range of Elements:

You can use slicing to access a range of items in a list:

Python
fruits = ["apple", "banana", "cherry", "date", "fig"]

# Get items from index 1 to 3 (excluding 3)
print(fruits[1:3])  # Output: ["banana", "cherry"]

# Get items from the beginning to index 2 (excluding 2)
print(fruits[:2])  # Output: ["apple", "banana"]

# Get items from index 2 to the end
print(fruits[2:])  # Output: ["cherry", "date", "fig"]

Slicing allows you to extract a part of a list. The syntax is list[start:end], where start is the index where the slice starts (inclusive), and end is the index where the slice ends (exclusive). If you omit start, it begins from the start of the list. If you omit end, it slices till the end of the list.

Accessing with Steps:

You can also specify a step, which determines how many items to skip between elements:

Python
fruits = ["apple", "banana", "cherry", "date", "fig", "grape"]

# Get every second item from index 0 to 4
print(fruits[0:5:2])  # Output: ["apple", "cherry", "fig"]

The step allows you to skip elements. The syntax is list[start:end:step]. In the example above, fruits[0:5:2] starts at index 0, ends before index 5, and takes every second item.

Accessing Nested Lists:

Python allows lists within lists, known as nested lists. Accessing elements in a nested list requires an additional index:

Python
nested_list = [["apple", "banana"], ["cherry", "date"], ["fig", "grape"]]

# Access "cherry"
print(nested_list[1][0])  # Output: cherry

To access elements in a nested list, you use multiple indexes. The first index accesses the main list, and the second index accesses the sub-list.

Accessing Lists with Loops:

You can also use loops to access and manipulate items in a list:

Python
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

Using a loop allows you to iterate through each item in the list and perform operations on them. This is particularly useful when you need to process or transform all elements in a list.