A Python list is a built-in data structure that can store multiple items in a single variable. Lists are created by placing a comma-separated sequence of sub-items enclosed in square brackets [ ].
The primary characteristics of Python lists are their mutability, which means they can be changed after they are created, and their ability to hold different data types. The elements of a list can be of any type, including numbers, strings, and even other lists.
Here a basic example of Python List
my_list = [1, 2, 'apple', 4.5]
print(my_list)
Output:
[1, 2, 'apple', 4.5]
Python lists are straightforward to create. At its simplest, a list can be defined by enclosing a comma-separated sequence of items in square brackets [ ].
Example 1 - Creating a list using different datatypes
# Creating an integer list
integer_list = [1, 2, 3, 4, 5]
print(integer_list)
# Creating a float list
float_list = [1.2, 2.3, 3.4, 4.5, 5.6]
print(float_list)
# Creating a string list
string_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']
print(string_list)
Output:
# integer_list
[1, 2, 3, 4, 5]
# float_list
[1.2, 2.3, 3.4, 4.5, 5.6]
# string_list
['apple', 'banana', 'cherry', 'date', 'elderberry']
Example 2 - Creating a list using mixed and duplicate items
# List with mixed types
mixed_list = [1, 'two', 3.0, True, [5, 6, 7]]
print(mixed_list)
# List with duplicate items
dup_list = [1, 2, 2, 3, 4, 4, 4, 5, 5, 5, 5]
print(dup_list)
# List with duplicate items (strings)
dup_list_strings = ['apple', 'banana', 'apple', 'cherry', 'banana', 'cherry']
print(dup_list_strings)
Output:
# List with mixed types
[1, 'two', 3.0, True, [5, 6, 7]]
# List with duplicate items
[1, 2, 2, 3, 4, 4, 4, 5, 5, 5, 5]
# List with duplicate items
['apple', 'banana', 'apple', 'cherry', 'banana', 'cherry']
Python lists offer robust options for manipulation. Elements in a list are assigned a unique index based on their position, starting from 0 for the first element. Using these indices, we can access, add, modify, or remove elements from the list. Slicing, another powerful feature, allows for accessing subsets of the list using a range of indices.
You can get to access any element in the list by referring to its index number. Remember, indexing in Python starts from 0, which means the first element is at position 0, the second at position 1, and so on.
Here's an example:
my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']
print(my_list[0])
print(my_list[2])
Output:
apple
cherry
Example of multi-dimensional list:
two_dim_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(two_dim_list[0][1])
two_dim_list_str = [["apple", "banana", "cherry"], ["dog", "cat", "mouse"]]
print(two_dim_list_str[1][0])
Output:
2
dog
Python also supports negative indexing, which allows you to start the index from the end of the list. -1 refers to the last item, -2 refers to the second-last item, and so on. Here's how you can use negative indexing:
my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']
print(my_list[-1])
print(my_list[-3])
Output:
elderberry
cherry
In Python, Slicing allows you to retrieve a section, or slice, of a list. You can slice a list by specifying the start index and the end index separated by a colon ‘:’. The start index is inclusive, and the end index is exclusive.
Example:
# Define a list of numbers
num_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
# Slicing from index 2 to 5 (exclusive)
print(num_list[2:5]) # Output: [30, 40, 50]
# Slicing from the start to index 3 (exclusive)
print(num_list[:3]) # Output: [10, 20, 30]
# Slicing from index 6 to the end
print(num_list[6:]) # Output: [70, 80, 90, 100]
# Slicing the last three items
print(num_list[-3:]) # Output: [80, 90, 100]
# Slicing every second item
print(num_list[::2]) # Output: [10, 30, 50, 70, 90]
Output:
[30, 40, 50]
[10, 20, 30]
[70, 80, 90, 100]
[80, 90, 100]
[10, 30, 50, 70, 90]
Lists in Python are mutable, so we can update the list using an assignment operator (=).
Example:
my_list_1 = ['apple', 'banana', 'cherry']
my_list[1] = 'blackberry'
print(my_list)
my_list_2 = ['apple', 'banana', 'cherry', 'date', 'elderberry']
my_list[1:3] = ['blackberry', 'citrus']
print(my_list)
Output:
['apple', 'blackberry', 'cherry']
['apple', 'blackberry', 'citrus', 'date', 'elderberry']
There are 3 ways to add elements to a list in Python. They are:
The append() method adds an element to the end of the list.
my_list = ['apple', 'banana', 'cherry']
my_list.append('date')
print(my_list)
Output:
['apple', 'banana', 'cherry', 'date']
In this example, 'date' is added to the end of the list.
The insert() method adds an element at a specified index. This method requires two arguments: the index at which to insert the new element and the new element itself.
my_list = ['apple', 'cherry', 'date']
# inserting an element at index 1 (second position)
my_list.insert(1, 'banana')
print(my_list)
Output:
['apple', 'banana', 'cherry', 'date']
The extend() method adds multiple elements to the end of the list. This method takes an iterable (like a list or a tuple) as an argument.
my_list = ['apple', 'banana', 'cherry']
my_list.extend(['date', 'elderberry'])
print(my_list)
Output:
['apple', 'banana', 'cherry', 'date', 'elderberry']
If you know the value of the item, you can use the remove() method, which removes the first occurrence of a value.
my_list = ['apple', 'banana', 'cherry']
my_list.remove('banana')
print(my_list)
Output:
['apple', 'cherry']
If you know the index of the item, you can use the pop() method, which removes the item at a specific index and returns it.
my_list = ['apple', 'banana', 'cherry']
my_list.pop(1)
print(my_list)
Output:
['apple', 'cherry']
Here, the pop() method removes the item at index 1, which is 'banana'.
If no index is specified, pop() removes and returns the last item in the list.
The del keyword in Python can also be used to remove items from a list. Like pop(), del removes an item at a specific index:
my_list = ['apple', 'banana', 'cherry']
del my_list[1]
print(my_list)
Output:
['apple', 'cherry']
The del keyword can also remove slices from a list or delete the entire list.
# remove a slice
my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']
del my_list[1:3] print(my_list)
# delete entire list
del my_list
Output:
['apple', 'date', 'elderberry']
Iterating through a list in Python is a common operation that allows you to access each item in the list, one at a time.
The for loop in Python iterates over the items of a sequence in the order that they appear.
my_list = ['apple', 'banana', 'cherry']
for item in my_list:
print(item)
Output:
apple
banana
cherry
List comprehension in Python is a powerful and compact way to create new lists by transforming the elements of an existing list (or any iterable) in a single, readable line of code.
Here’s an example of a list comprehension
# Example 1: Squares of all numbers in the list
numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers]
print(squares)
# Example 2: Squares of numbers greater than 2 in the list
numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers if n > 2]
print(squares)
Output:
[1, 4, 9, 16, 25]
9, 16, 25]
Python Lists:
Creating Lists:
Accessing List Items:
Slicing Lists:
Updating Lists:
Adding Items to Lists:
Removing Items from Lists:
Iterating Through Lists:
List Comprehension: