Python Lists: Everything You Need to Know with Example Code Snippets
Python lists are one of the most fundamental data structures that Python offers. It is a sequence data type, allowing us to store multiple values in one container. Lists are mutable, which means that we can add, remove, or modify items within the list.
In this blog, we’ll cover everything you need to know about Python lists, including creating, accessing, and modifying lists, as well as some useful methods that come with Python’s list data type.
Creating a List
We can create a list in Python by enclosing a sequence of items in square brackets []. Here is an example of creating a list of integers:
my_list = [1, 2, 3, 4, 5]
We can also create a list of strings:
my_list = ['apple', 'banana', 'cherry', 'date']
Python also allows us to create an empty list:
my_list = []
Accessing Elements in a List
We can access individual elements in a list using their index. In Python, lists are zero-indexed, which means that the first element is at index 0, the second element is at index 1, and so on.
Here is an example of accessing elements in a list:
my_list = [1, 2, 3, 4, 5] # Accessing the first element in the list print(my_list[0]) # Accessing the third element in the list print(my_list[2]) # Accessing the last element in the list print(my_list[-1])
Output:
1 3 5
Modifying a List
As we mentioned earlier, lists are mutable, which means that we can add, remove, or modify items within the list. Here are some common ways to modify a list:
Adding Elements to a List
We can add elements to a list using the append() method, which adds an element to the end of the list.
my_list = [1, 2, 3, 4, 5] # Adding a new element to the end of the list my_list.append(6) print(my_list)
Output:
[1, 2, 3, 4, 5, 6]
We can also add multiple elements to a list using the extend() method, which takes an iterable as an argument.
my_list = [1, 2, 3, 4, 5] # Adding multiple elements to the end of the list my_list.extend([6, 7, 8]) print(my_list)
Output:
[1, 2, 3, 4, 5, 6, 7, 8]
Removing Elements from a List
We can remove elements from a list using the remove() method, which removes the first occurrence of the specified element.
my_list = [1, 2, 3, 4, 5] # Removing an element from the list my_list.remove(3) print(my_list)
Output:
[1, 2, 4, 5]
We can also remove elements from a list using the del statement, which removes an element at a specified index.
my_list = [1, 2, 3, 4, 5] # Removing an element at index 2 del my_list[2] print(my_list)
Output:
[1, 2, 4, 5]