Python Lists
A Python list is a built-in data structure that allows you to store multiple items in a single variable. Lists are ordered, mutable, and contain elements of different data types such as integers, floats, strings, and other lists.
Creating a List
Lists are defined using square brackets []
, with elements 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.
For example:
# Creating a list from a tuple
my_list = list((1, 2, 3, 4))
print(my_list) # [1, 2, 3, 4]
# Creating a list from a string
char_list = list("james")
print(char_list) # ['j', 'a', 'm', 'e', 's']
# Empty list
empty_list = list()
print(empty_list) # []
Accessing List Elements
You can access individual elements in a list using square brackets []
with the index of the element. Python list use zero-based indexing, meaning the first element has an index of 0
, the second element has an index of 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
Negative Indexing
Python list also supports negative indexing, which allows you to access elements from the end of the list. The last item is indexed as -1
, the second last as -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
Slicing
Slicing allows you to access a range of items. The syntax of slicing is: list[start:end:step]
, where
start
: The starting index (inclusive).stop
: The ending index (exclusive).step
: The interval between elements (optional).
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']
If you omit the start
value, Python assumes the slice starts at the beginning of the list (index 0
).
If you omit the end
value, Python extends the slice to the end of the list (including the last element).
If you omit both the start
and end
values, Python returns the entire list.
Modifying Lists
Python lists are mutable, meaning you can change their elements after the list has been created.
(1) Changing Elements by Index
You can change the value of a specific item in a list by referencing its index.
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]
(2) Adding Elements to a List
There are several ways to add new elements to a list.
(a) 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]
(b) 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]
(c) 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]
(3) Removing Elements from a List
There are several ways to remove elements from a list.
(a) 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]
(b) Using pop()
The pop()
method removes an element at a specified index and returns it. If no index is provided, it removes the last element.
For example:
my_list = [5, 10, 15, 20]
my_list.pop(1)
print(my_list) # Output: [5, 15, 20]
my_list.pop()
print(my_list) # Output: [5, 15]
(c) Using del
Statement
The del
statement can be used to delete an element at a specified index or even 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.
(d) 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 elements 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 Lists
You can use a for
loop to iterate through the elements of a list.
For example:
my_list = [5, 10, 15, 20]
# Iterating through the list
for item in my_list:
print(item)
Output:
5
10
15
20
List Comprehensions
List comprehension provides a concise way to create lists based on existing lists or other iterable objects. It allows you to generate a new list by applying an expression to each element of an iterable (such as a list, range, or string) in a single line.
Syntax of List Comprehension:
[expression for item in iterable if condition]
Example of List Comprehension:
my_list = [1, 2, 3, 4]
# Using list comprehension to get the square of each number
square = [x**2 for x in my_list]
print(square) # [1, 4, 9, 16]
Explanation:
The list comprehension [x**2 for x in my_list]
iterates through each element x
in my_list
.
The expression x**2
calculates the square of each element, and the result is stored in the new squares
list.