Accessing Items

  • This lesson explains how to retrieve values from a Python list using index numbers and negative indexing.

  • Accessing items in a list means retrieving elements from the list using their position (index).

    Since lists are ordered, every item has a fixed position, starting from index 0.

Accessing List Items Using Index

Each item in a list has a position number called an index. Index starts from 0.

fruits = ["Apple", "Mango", "Banana", "Orange"]

print(fruits[0])  # First item
print(fruits[2])  # Third item

Negative Indexing

Python allows accessing items from the end using negative index. -1 → Last item , -2 → Second last

numbers = [10, 20, 30, 40, 50]

print(numbers[-1])  # Last item
print(numbers[-2])  # Second last

Accessing a Range of Items (Slicing)

Slicing is used to access multiple items from a list.

colors = ["Red", "Green", "Blue", "Yellow", "Pink"]

print(colors[1:4])  # From index 1 to 3

Slicing From Beginning

If start index is not given, Python starts from the beginning.

colors = ["Red", "Green", "Blue", "Yellow", "Pink"]
print(colors[:3])

Slicing Till End

If end index is not given, Python goes till the last item.

colors = ["Red", "Green", "Blue", "Yellow", "Pink"]
print(colors[2:])

Check if Item Exists

We use in keyword to check if an item is present in the list.

fruits = ["Apple", "Mango", "Banana"]

if "Mango" in fruits:
    print("Mango is in the list")