Lists are one of the most versatile and commonly used data structures in Python.
Lists allow you to store and manipulate collections of items in an ordered and mutable fashion.
Learning how to work with lists in Python will build your skills as a programmer and boost your ability to work with data structures and algorithms.
Basics Of Lists In Python
A list is an ordered collection of items and can be any data type, meaning a list can contain strings and integers in one list.
Lists are also mutable, meaning you can change, add, or remove elements from the list after its created.
Creating A List
To create a list, use square brackets []
to wrap the collection of items or use the list()
constructor.
pythonnumbers = [1, 2, 3, 4] numbers = list((1, 2, 3, 4)) empty_list = [] empty_list = list()
Accessing List Elements
To access elements in a list, you can refer to their index or use slicing to access a range of elements.
Keep in mind that Python uses zero-based indexing, so the first item of a list is at index 0.
Accessing an element by its index:
pythonvehicles = ["car", "truck", "motorcycle"] print(vehicles[1]) # Output: truck
Accessing elements in a list with slicing:
pythonfruits = ["apple", "banana", "raspberry", "pineapple", "blackberry"] print(fruits[1:3]) # Output: ['banana', 'raspberry', 'pineapple'] print(fruits[-3:]) # Output: ['raspberry', pineapple', 'blackberry'] print(fruits[:3]) # Output: ['apple', 'banana', 'raspberry']
Modifying Lists
Due to lists mutable property, they can be modified after creation with the ability to add, update, and remove elements.
Adding Elements
To add an element to the end of a list, use the append()
method:
pythonvehicles = ["car", "truck", "motorcycle"] vehicles.append("bicycle") print(vehicles) # Output: ["car", "truck", "motorcycle", "bicycle"]
To add an element at a specific index of a list, use the insert()
method.
The insert()
method works by taking two parameters: (index, item)
.
pythonvehicles = ["car", "truck", "motorcycle"] vehicles.insert(1, "bicycle") print(vehicles) # Output: ["car", "bicycle", "truck", motorcycle"]
To add multiple elements at once to the end of the list, use the extend()
method:
pythonvehicles = ["car", "truck", "motorcycle"] vehicles.extend(["bicycle", "airplane"]) print(vehicles) # Output: ["car", "truck", "motorcycle", "bicycle", "airplane"]
Updating Elements
To update the value of an element, access the element by its index and assign a new value:
pythonvehicles = ["car", "truck", "motorcycle"] vehicles[0] = "airplane" print(vehicles) # Output: ["airplane", "truck", "motorcycle"]
Removing Elements
To remove the first occurrence of an element, use the remove()
method:
pythonvehicles = ["car", "truck", "motorcycle"] vehicles.remove("truck") print(vehicles) # Output: ["car", "motorcycle"]
To remove an element by index and return it, use the pop
method. If no index is specified, the last element will be removed and returned:
python# Using pop() with a specified index vehicles = ["car", "truck", "motorcycle"] removed_vehicle = vehicles.pop(1) print(removed_vehicle) # Output: truck print(vehicles) # Output: ["car", "motorcycle"] # Using pop() with no specified index vehicles = ["car", "truck", "motorcycle"] last_vehicle = vehicles.pop() print(last_vehicle) # Output: motorcycle print(vehicles) # Output: ["car", "truck"]
To remove all elements from a list, use the clear
method:
pythonvehicles = ["car", "truck", "motorcycle"] vehicles.clear() print(vehicles) # Output: []
List Operations
There are a variety of operations to be used on lists to manipulate and analyze them.
The most common examples include concatenation, repetition, membership test, and list length.
Combining two lists using concatenation with the +
operator:
pythonlist1 = [1, 2, 3] list2 = [4, 5, 6] combined = list1 + list2 print(combined) # Output: [1, 2, 3, 4, 5, 6]
Repeating the elements in a list using the *
operator:
pythonrepeated_list = [1, 2, 3] * 3 print(repeated_list) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]
Checking if an element is in a list with the membership test using the in
operator:
pythonfruits = ["apple", "banana", "cherry"] print("banana" in fruits) # Output: True print("grape" in fruits) # Output: False
Finding the number of elements in a list using the len()
function:
pythonfruits = ["apple", "banana", "cherry"] print(len(fruits)) # Output: 3
Sorting And Reversing Lists
Python has built in methods to help with sorting and reversing lists.
Sorting Lists
To sort the list in place, use the sort()
method:
pythonfruits = ["cherry", "apple", "banana"] fruits.sort() print(fruits) # Output: ['apple', 'banana', 'cherry']
To return a new sorted list without changing the original list, use the sorted()
method:
pythonfruits = ["cherry", "apple", "banana"] sorted_fruits = sorted(fruits) print(sorted_fruits) # Output: ['apple', 'banana', 'cherry'] print(fruit) # Output: ['cherry', 'apple', 'banana']
Reversing Lists
To reverse the list in place, use the reverse()
method:
pythonfruits = ["cherry", "apple", "banana"] fruits.reverse() print(fruits) # Output: ['banana', 'apple', 'cherry']
Copying Lists
To copy a list in Python, you can use slicing, the copy()
method, or the list()
method.
Copying a list using slicing:
pythonfruits = ["apple", "banana", "cherry"] fruits_copy = fruits[:]
Copying a list using the copy()
method:
pythonfruits = ["apple", "banana", "cherry"] fruits_copy = fruits.copy()
Copying a list using the list()
method:
pythonfruits = ["apple", "banana", "cherry"] fruits_copy = list(fruits)
Advanced List Techniques
To combine multiple lists in Python, use the zip()
function:
pythonnames = ["Andrew", "Jackie", "Elie"] ages = [22, 21, 25] combined = list(zip(names, ages)) print(combined) # Output: [('Andrew', 21), ('Jackie', 21), ('Elie', 25)]
Flattening a list of lists into a single list:
pythonmatrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flat_list = [num for row in matrix for num in row] print(flat_list) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
To find the index of an element, use the index()
method:
pythonfruits = ["apple", "banana", "cherry"] index = fruits.index("banana") print(index) # Output: 1
To count how many times an element appear in a list, use the count()
method:
pythonnumbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] count_of_twos = numbers.count(2) print(count_of_twos) # Output: 2
Conclusion
Lists are a powerful and flexible data structure in Python. There are several built-in functions and methods that help in performing complex operations to analyze and manipulate the data. Learning about lists in Python will help grow your skills as a programmer.