Accessing List Elements

Lists allow you to access individual elements and sublists (or “slices”) through indexing and slicing. Here’s an overview of how these work:

Accessing Individual Elements with Indexing

Each element in a list is associated with an index number, starting from 0 for the first element. You can access elements directly by specifying their index in square brackets.

# Example list
fruits = ['apple', 'banana', 'cherry', 'date']

# Accessing the first element
print(fruits[0])  # Output: 'apple'

# Accessing the third element
print(fruits[2])  # Output: 'cherry'

Negative Indexing

Python also supports negative indexing, where -1 refers to the last element, -2 to the second-to-last, and so on.

# Accessing the last element
print(fruits[-1])  # Output: 'date'

# Accessing the second-to-last element
print(fruits[-2])  # Output: 'cherry'

Accessing Subsections with Slicing

Slicing allows you to retrieve a range of elements from a list. This is done using the syntax list[start:stop:step], where:

  • start is the index at which to begin (inclusive).
  • stop is the index at which to end (exclusive).
  • step determines the stride between elements (optional).

Basic Slicing

To extract a portion of a list, specify the start and stop indices.

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

Omitting Start or Stop

If you omit the start or stop indices, Python assumes you mean from the beginning or to the end of the list, respectively.

# Get all elements from the beginning to index 2 (exclusive)
print(fruits[:2])  # Output: ['apple', 'banana']

# Get all elements from index 1 to the end
print(fruits[1:])  # Output: ['banana', 'cherry', 'date']

Using Step in Slicing

The step value allows you to specify the interval between elements.

# Get every second element
print(fruits[::2])  # Output: ['apple', 'cherry']

# Reverse the list
print(fruits[::-1])  # Output: ['date', 'cherry', 'banana', 'apple']

Summary

  • Indexing: Use square brackets with an integer index to get a single element.
  • Negative Indexing: Use negative indices to count from the end of the list.
  • Slicing: Use start:stop:step to extract sublists and customize intervals.