Python Lists
A Python list is a built-in data structure that allows you to store multiple items (elements) in a single variable. Lists are ordered, mutable, and contain elements of different data types such as integers, floats, strings, and other lists.
In Python, you use the list to store collections of items, such as names of persons, items in a shopping cart, or game scores.
Creating a List
In Python, lists are defined using square brackets []
, and elements are separated by commas.
For example:
# Creating a list of integers
my_list = [1, 2, 3, 4]
# List of mixed data types
mixed_list = [5, "Hello", 22.1, True]
# Empty List
empty_list = []
You can also create a list by passing an iterable such as a tuple or string to the list()
constructor. It is particularly useful if you want to convert another iterable like a tuple or string, into a list.
For example:
# Creating a list from a tuple
my_list = list((1, 2, 3, 4))
print(my_list) # Output: [1, 2, 3, 4]
# Creating a list from a string
char_list = list("james")
print(char_list) # Output: ['j', 'a', 'm', 'e', 's']
# Empty list
empty_list = list()
print(empty_list) # Output: []
Accessing List Elements
To access elements of a list, use the list name followed by the index (or position) of the desired element in square brackets (e.g. list_name[0]
). Python lists use zero-based indexing, so the first element is at index 0
, the second element is at index 1
, and so on.
For example:
my_list = ["apple", "banana", "mango", "orange"]
# Accessing the first element
print(my_list[0]) # Output: apple
# Accessing the second element
print(my_list[1]) # Output: banana
Using values from a list
You can use individual values from the list in the same way you would use any other variable.
For example:
my_list = ["apple", "banana", "mango", "orange"]
print(f"The price of {my_list[1]} is $2")
numbers = [1, 2, 3, 4]
print(numbers[2] + 2)
Output:
The price of banana is $2
5
Negative Indexing
Python list also supports negative indexing, which allows you to access elements from the end of the list. The last item is at index -1
, the second last at -2
, and so on.
For example:
my_list = ["apple", "banana", "mango", "orange"]
# Accessing the last element
print(my_list[-1]) # Output: orange
# Accessing the second last element
print(my_list[-2]) # Output: mango
List Slicing
List slicing allows you to extract a portion of a list by specifying a range of indices.
The syntax for slicing a list is:
list[start:end:step]
start
(Optional): The index where the slice starts (inclusive). If omitted, it defaults to the beginning of the list (index 0
).
end
(Optional): The index where the slice ends (exclusive). If omitted, it defaults to the end of the list.
step
(Optional): The step size between elements. If omitted, it defaults to 1
.
For example:
my_list = ["apple", "banana", "mango", "orange", "pineapple"]
# Accessing elements from index 1 to 3 (excluding the element at index 3)
print(my_list[1:3]) # Output: ['banana', 'mango']
# Accessing all elements starting from index 2
print(my_list[2:]) # Output: ['mango', 'orange', 'pineapple']
# Accessing all elements up to, but not including, the last element
print(my_list[:-1]) # Output: ['apple', 'banana', 'mango', 'orange']
# Accessing all elements from start to end (entire list)
print(my_list[:])
# Output: ['apple', 'banana', 'mango', 'orange', 'pineapple']
# Accessing elements with a step of 2 (every second element)
print(my_list[::2]) # Ouput: ['apple', 'mango', 'pineapple']
Python lists are mutable, meaning you can change their elements after the list has been created.
Adding Items to a List
There are several ways to add new elements to a list.
Using append()
The append()
method adds a single element to the end of the list.
For example:
my_list = [5, 10, 15]
my_list.append(20)
print(my_list) # Output: [5, 10, 15, 20]
Using insert()
The insert()
method allows you to insert an element at a specific position in the list.
For example:
my_list = [5, 10, 15]
my_list.insert(1, 99)
print(my_list) # Output: [5, 99, 10, 15]
Using extend()
The extend()
method allows you to add multiple elements from another iterable (like a list or tuple) to the end of the list.
For example:
my_list = [5, 10, 15]
my_list.extend([20, 25, 30])
print(my_list) # Output: [5, 10, 15, 20, 25, 30]
Change List Items
To change items of a list, use the name of the list followed by the index of the item you want to change inside square brackets and assign a new value.
For example:
my_list = [5, 10, 15, 20]
# Modify the element at index 1
my_list[1] = 30
print(my_list) # Output: [5, 30, 15, 20]
Removing Items from a List
There are several ways to remove items from a list.
Using remove()
The remove()
method removes the first occurrence of a specific value from the list.
For example:
my_list = [5, 10, 15, 5]
my_list.remove(5)
print(my_list) # Output: [10, 15, 5]
Using pop()
The pop()
method removes an element at a specified index and returns it. If no index is provided, the last element is removed.
For example:
my_list = [5, 10, 15, 20]
# Removing and returning the item at index '1'
removed_value = my_list.pop(1)
print(removed_value) # Output: 10
# Removing and returning the last item
removed_value = my_list.pop()
print(removed_value) # Output: 20
Using del
Statement
The del
statement can be used to delete an item at a specified index or remove the entire list.
For example:
my_list = [5, 10, 15, 20, 25]
# Using del to remove an element at index 2
del my_list[2]
print(my_list) # Output: [5, 10, 20, 25]
# Using del to remove a slice of elements
del my_list[2:]
print(my_list) # Output: [5, 10]
# Using del to delete the entire list
del my_list
# Trying to print my_list will raise an error since it's deleted
# print(my_list)
Once a list is deleted, it is no longer accessible and will raise a NameError
if you try to reference it.
Using clear()
The clear()
method removes all elements from the list, resulting in an empty list.
For example:
my_list = [5, 10, 15, 20]
# Using clear() to remove all elements
my_list.clear()
print(my_list) # Output: []
List Length
You can find the length of a list (i.e., the number of items it contains) using the built-in len()
function.
For example:
my_list = [5, 10, 15, 20]
# Using len() to get the length of the list
length = len(my_list)
print(length) # Output: 4
Iterating Through a List
In Python, we iterate through a list to access and process each item individually. This is useful for performing operations such as printing, modifying, filtering based on conditions, or transforming data.
You can use a for
loop to iterate through the elements of a list.
For example, let’s iterate through a list and print each item.
my_list = [5, 10, 15, 20]
# Iterating through the list
for item in my_list:
print(item)
Output:
5
10
15
20
Let’s take a look at another example. Let’s filter even numbers from a list.
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
even_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
print(even_numbers) # Output: [2, 4, 6, 8]
In the above code, we iterate through each number (num
) in numbers
list and check if it is divisible by 2
using the condition num % 2 == 0
. The symbol %
is a modulus operator, which gives the remainder after division. If num
divided by 2 leaves no remainder (0
), it’s even. When the condition is True
, we add the number to the even_numbers
list using the append()
method. In the end, even_numbers
list contains only the even numbers from the original list.
Python List Methods
Python provides built-in list methods to perform common operations on lists.
Here’s a table of all the list methods:
Method | Description |
append(item) | Adds a single item to the end of the list. |
pop(index) | Removes and returns the item at the given index (default: last item). |
remove(item) | Removes the first occurrence of the specified item. |
extend(iterable) | Adds all elements from the given iterable (e.g. another list) to the end of the list. |
sort() | Sorts the list in ascending order. |
reverse() | Reverses the order of the list in-place. |
insert(index, item) | Inserts an item at the specified index. |
index(item) | Returns the index of the first occurrence of the specified item. |
count(item) | Counts the number of times the specified item appears in the list. |
clear() | Removes all the items from the list, leaving it empty. |
copy() | Creates a shallow copy of the list. |