Lists and Tuples
Operations on lists and tuples often rely on loops and list comprehensions. While we introduce lists and tuples early to establish core concepts, beginners may want to review control flow first. Re-visiting lists and tuples after learning loops will make advanced operations much easier to grasp.
Common tasks like searching and sorting are discussed in detail in the algorithm chapters, such as the Array section.
Creating Lists
A list is an ordered collection of items and is one of the most versatile built-in data structures in Python. To create a list, place comma-separated values inside square brackets [ ]:
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "apple", 3.5]
You can also convert other iterable objects into lists using the list() constructor function:
# Create a list from a tuple
tup = (1, 2, 3)
list_from_tuple = list(tup) # Result: [1, 2, 3]
# Create a list of characters from a string
string = "hello"
list_from_string = list(string) # Result: ['h', 'e', 'l', 'l', 'o']
Keep the list() function in mind; we will cover iterables and tuples in depth later in this chapter.
List comprehensions are another popular way to generate lists, which we cover in the Functional Programming section.
Accessing List Elements
Indexing
Like strings, lists are ordered, and each item has a unique index starting at 0. You can retrieve an item by placing its index in square brackets:
fruits = ["apple", "banana", "orange", "pineapple"]
print(fruits[0]) # Output: apple
print(fruits[2]) # Output: orange
Negative indices count backward from the end of the list: -1 refers to the last element, -2 to the second-to-last, and so on.
fruits = ["apple", "banana", "orange", "pineapple"]
print(fruits[-1]) # Output: pineapple
print(fruits[-2]) # Output: orange
Slicing
You can extract a sublist using slicing (list[start:end]). Like string slicing, the start index is inclusive, while the end index is exclusive. Omitting the start index defaults to the beginning of the list, and omitting the end index defaults to the end of the list:
fruits = ["apple", "banana", "orange", "pineapple"]
# Get elements from index 1 to 3 (indexes 1, 2, 3)
print(fruits[1:4]) # Output: ['banana', 'orange', 'pineapple']
# Get elements from the start up to index 3
print(fruits[:3]) # Output: ['apple', 'banana', 'orange']
# Get elements from index 2 to the end
print(fruits[1:]) # Output: ['banana', 'orange', 'pineapple']
You can also specify a step size as a third parameter inside the slice:
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[::2]) # Step of 2, selects even numbers, Output: [0, 2, 4, 6, 8]
Setting the step to -1 offers a concise way to reverse a list (creating a new reversed list):
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[::-1]) # Reverse order, Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
While a step size can be useful, combining it with start and end indices can make code difficult to read. Try to avoid overly complex slices like the following. (Can you guess what this outputs?)
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[-2:2:-3]) # Output: ??
Explanation: Starting at index -2 (value 8), step backward by 3 (moving left) and stop before index 2 (value 2). This selects 8 and 5.
Python also supports a powerful feature for extracting elements: unpacking.