No posts available in this category.

Python Lists

Add to Favorites

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.

python
numbers = [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:

python
vehicles = ["car", "truck", "motorcycle"] print(vehicles[1]) # Output: truck

Accessing elements in a list with slicing:

python
fruits = ["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:

python
vehicles = ["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) .

python
vehicles = ["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:

python
vehicles = ["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:

python
vehicles = ["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:

python
vehicles = ["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:

python
vehicles = ["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:

python
list1 = [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:

python
repeated_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:

python
fruits = ["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:

python
fruits = ["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:

python
fruits = ["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:

python
fruits = ["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:

python
fruits = ["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:

python
fruits = ["apple", "banana", "cherry"] fruits_copy = fruits[:]

Copying a list using the copy() method:

python
fruits = ["apple", "banana", "cherry"] fruits_copy = fruits.copy()

Copying a list using the list() method:

python
fruits = ["apple", "banana", "cherry"] fruits_copy = list(fruits)

Advanced List Techniques

To combine multiple lists in Python, use the zip() function:

python
names = ["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:

python
matrix = [[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:

python
fruits = ["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:

python
numbers = [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.