Understanding Python List Indexing and Slicing
This article explains Python's list data structure, covering forward and negative indexing as well as slice operations, and provides multiple code examples demonstrating element access, sub‑list extraction, list copying, reversal, and stepwise selection.
In Python, a list is an ordered, mutable data structure used to store collections. Each element has a unique index starting from 0, and Python offers powerful indexing and slicing capabilities to access and manipulate list elements.
Basic Indexing
Forward indexing counts from the beginning of the list, with the first element at index 0.
my_list = ['apple', 'banana', 'cherry', 'date']
print(my_list[0]) # Output: appleNegative indexing counts from the end of the list, where the last element has index -1.
print(my_list[-1]) # Output: date
print(my_list[-2]) # Output: cherrySlice Operations
Slicing allows you to obtain a contiguous subset of list elements. The syntax is list[start:end] , where start is inclusive and end is exclusive. An optional step can be specified as list[start:end:step] .
# Omit start: defaults to beginning of the list.
# Omit end: defaults to the end of the list.
# step: interval between elements, default is 1.
print(my_list[1:3]) # Output: ['banana', 'cherry']
print(my_list[:2]) # Output: ['apple', 'banana']
print(my_list[2:]) # Output: ['cherry', 'date']
print(my_list[::2]) # Output: ['apple', 'cherry']
print(my_list[::-1]) # Output: ['date', 'cherry', 'banana', 'apple']Example 1: Extracting a middle segment
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
middle_part = numbers[3:6]
print(middle_part) # Output: [3, 4, 5]Example 2: Copying an entire list
original_list = ['a', 'b', 'c', 'd']
copied_list = original_list[:]
print(copied_list) # Output: ['a', 'b', 'c', 'd']Example 3: Reversing a list
fruits = ['apple', 'banana', 'cherry', 'date']
reversed_fruits = fruits[::-1]
print(reversed_fruits) # Output: ['date', 'cherry', 'banana', 'apple']Example 4: Selecting every second element
data = [i for i in range(10)]
every_second = data[::2]
print(every_second) # Output: [0, 2, 4, 6, 8]Example 5: Using negative indices and slicing to get the last elements
items = ['item1', 'item2', 'item3', 'item4', 'item5']
last_two = items[-2:]
print(last_two) # Output: ['item4', 'item5']Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.