MWZ

MINDWAREZONE

Access List Items

Lists in Python store multiple items in a specific order. You can access these items using their index positions.

Positive Indexing

  • Positive indexing starts from 0.
  • The first element has index 0, the second has index 1, and so on.

Example 1:

fruits = ["Apple", "Banana", "Mango", "Orange"]
print(fruits[0])
            

Output

Apple
            

Example 2:

numbers = [10, 20, 30, 40]
print(numbers[2])
            

Output

30
            

Negative Indexing

  • Negative indexing starts from -1.
  • -1 refers to the last element, -2 to the second last element, and so forth.
  • It is useful when you want to access elements from the end of the list.

Example

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

print(fruits[-1])
            

Output:

Orange
            

Example 2:

numbers = [10, 20, 30, 40]

print(numbers[-2])
            

Output:

30
            

Accessing Multiple Elements

Multiple elements can be accessed using slicing.

The syntax is:

list_name[start:end]
            

  The start index is included, while the end index is excluded.  

Example 1:

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

print(fruits[1:4])
            

Output:

['Banana', 'Mango', 'Orange']
            

Example 2:

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

print(numbers[:3])   # First three elements
print(numbers[3:])   # Elements from index 3 onward
            

Output:

[10, 20, 30]
[40, 50, 60]