The most popular collection of items in Python is a list. Unlike other languages like C or Java, Python does not have arrays, but lists in Python are equivalent to arrays, except they are dynamic.
Here is a summary of Lists in Python:
Lists are used to store multiple items in a single variable.
Lists are created using square brackets:
fruits = ["Apple", "Banana", "Cherry"]
List items are ordered, changeable and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] and so on.
We can access list items using the index:
fruits[0]
- We can change list items using the index:
fruits[0] = "Orange"
- We can check if an item exists using the 'in' keyword:
"Apple" in fruits
- We can iterate through list items using a for loop:
for x in fruits:
print(x)
- We can add items to the end of a list using append():
fruits.append("Mango")
- We can insert an item at a specific index using insert():
fruits.insert(1, "Grapes")
Use-Cases
Here are some common use-cases for lists in Python:
Storing collections of data - Lists are used to store data that are related or of the same type. For example, a list of student names, a list of product prices, etc.
Representing sequences - Lists are naturally suited to represent sequences of data like the moves of a chess game, the cards in a deck, etc.
Function arguments - Functions can take lists as arguments. This allows the function to operate on multiple elements at the same time.
Implementing other data structures - Many other data structures like stacks, queues, sets, etc. can be implemented using lists in Python.
Looping - We can easily loop through list items using a for loop. This allows us to perform some operations on each item.
Algorithm implementation - Many algorithms require lists to store intermediate data and results. For example, sorting algorithms.
Storing heterogeneous data - Lists can store elements of different types. This makes it a very flexible data type.
Default argument value - We can use an empty list [] as a default argument value. The list is created once when the function is defined.
So in summary, lists are a very useful and versatile data type in Python due to their flexibility, ease of use and variety of operations supported.
List Slicing
List slicing in Python allows you to select a subset of list elements.
SlicingIt is done by specifying indices inside square brackets, separated by a colon:
[start_index:end_index]
Some things to note:
The start index is inclusive, while the end index is exclusive.
If the start index is omitted, it defaults to 0.
If the end index is omitted, it defaults to the length of the list.
The indices can be negative to start from the end of the list.
For example:
fruits = ["Apple", "Banana", "Cherry", "Mango"]
fruits[1:3] # Returns ["Banana", "Cherry"]
fruits[:3] # Returns ["Apple", "Banana", "Cherry"]
fruits[2:] # Returns ["Cherry", "Mango"]
fruits[-3:] # Returns ["Cherry", "Mango"]
You can also assign values to a slice to update multiple elements at once:
fruits[1:3] = ["Orange", "Grapes"]
print(fruits)
# ['Apple', 'Orange', 'Grapes', 'Mango']
So in short, list slicing allows you to select a subset of list elements in a compact syntax, which is very useful for manipulating lists.
List Comprehension
List comprehension in Python provides a concise way to create lists.
It consists of an expression followed by a for loop, inside square brackets:
[expression for item in list]
For example, to create a list of squares of numbers from 1 to 10, we can do:
squares = [i*i for i in range(1,11)]
print(squares)
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
We can also add if conditions to filter the list:
even_squares = [i*i for i in range(1,11) if i%2 == 0]
print(even_squares)
# [4, 16, 36, 64, 100]
We can use multiple for loops to create cartesian products:
cartesian = [(x, y) for x in [1,2,3] for y in [3,1,4] ]
print(cartesian)Hope this explanation helps! Let me know if you have any other doubts.
# [(1, 3), (1, 1), (1, 4), (2, 3), (2, 1), (2, 4), (3, 3), (3, 1), (3, 4)]
The main advantages of list comprehension are:
More compact and concise syntax.
Easy to read and understand.
Faster performance compared to equivalent list operations.
So in short, list comprehension provides an elegant way to define and create lists based on existing sequences in Python.
List Filters
Filtering a list in Python involves creating a new list based on satisfying certain conditions.
It can be done in two ways:
- Using list comprehension:
new_list = [element for element in original_list if condition]
For example:
numbers = [1, 2, 3, 4, 5, 6]
even = [n for n in numbers if n%2 == 0]
print(even) # [2, 4, 6]
Here we are filtering the numbers list to only include even numbers.
- Using the filter() function:
new_list = list(filter(lambda x: condition, original_list))
For example:
numbers = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x%2 == 0, numbers))
print(even) # [2, 4, 6]
Here we are using a lambda function to check if a number is even, and filtering the numbers list accordingly.
In both cases, we are creating a new list (even) that contains only the elements from the original list (numbers) that satisfy the condition (being even).
The list comprehension approach is more Pythonic and readable, while the filter() approach may be slightly faster for large lists.
So in summary, filtering a list allows you to select specific elements from a list based on a condition, creating a new filtered list.
Mapping Function
Mapping a function to a list in Python applies the given function to each element of the list, and returns a list with the results.
It can be done using the map() function:
result_list = list(map(function, list))
For example:
numbers = [1, 2, 3, 4]
square = list(map(lambda x: x*x , numbers))
print(square) # [1, 4, 9, 16]
Here we are mapping a lambda function that squares a number to each element of the numbers list.
We can also map functions defined separately:
def square(x):
return x*x
square_list = list(map(square, numbers))
print(square_list) # [1, 4, 9, 16]
Here we are mapping the square() function to the numbers list.
The map() function applies the given function to each element and returns a map object, which we then convert to a list using list().
Some advantages of using map() are:
It's concise and readable.
It's efficient since it uses iterators.
So in summary, mapping a function to a list in Python allows you to apply the same transformation to each element of the list.
Parameter
A list is passed to a function as an argument by reference in Python, not by copy. This means that any changes made to the list inside the function will be reflected outside the function as well. For example:
def change_list(input_list):
input_list.append(100)
print("Inside function:", input_list)
num_list = [1,2,3]
change_list(num_list)
print("Outside function:", num_list)
Output: Inside function: [1, 2, 3, 100] Outside function: [1, 2, 3, 100]
And passing a copy:
def change_list(input_list):
input_list.append(100)
print("Inside function:", input_list)
num_list = [1,2,3]
change_list(list(num_list))
print("Outside function:", num_list)
Output: Inside function: [1, 2, 3, 100] Outside function: [1, 2, 3]
Here we used:
num_list as the variable name for the original list
input_list as the variable name for the list argument passed to the function
This makes it clearer which list we are referring to at any point in the code. More descriptive variable names can help improve the readability and maintainability of code.
List unpacking
List unpacking and rest operators are useful techniques in Python to extract elements from lists.
List unpacking allows you to assign multiple variables at once from a list:
fruits = ["Apple", "Banana", "Cherry"]
fruit1, fruit2, fruit3 = fruits
print(fruit1) # Apple
print(fruit2) # Banana
print(fruit3) # Cherry
Here we unpacked the fruits list into 3 variables: fruit1, fruit2 and fruit3.
You can also unpack into a smaller number of variables:
fruit1, fruit2, fruit3 = fruits
print(fruit1) # Apple
print(fruit2) # Banana
Here fruit3 is ignored since we only unpacked into 2 variables.
The rest operator *
allows you to assign remaining elements to a variable:
fruits = ["Apple", "Banana", "Cherry", "Mango"]
fruit1, *rest = fruits
print(fruit1) # Apple
print(rest) # ['Banana', 'Cherry', 'Mango']
Here *rest
collects all remaining elements into the rest list.
You can also combine rest operator with normal variables:
fruit1, fruit2, *rest = fruits
print(fruit1) # Apple
print(fruit2) # Banana
print(rest) # ['Cherry', 'Mango']
Here fruit1 and fruit2 are unpacked normally, and the rest collects the remaining elements.
In summary, list unpacking allows you to assign list elements to multiple variables in one line. The rest operator allows you to collect the remaining elements into a variable.
This makes code more concise and readable compared to accessing list elements by index.
Ignore Elements: When unpacking a list, you can use:
_
(underscore) variable - to ignore certain elements*
(star operator) - to collect remaining elements
For example:
fruits = ["Apple", "Banana", "Cherry", "Mango"]
_, fruit2, _ , fruit4 = fruits
print(fruit2) # Banana
print(fruit4) # Mango
Here we used _
to ignore the first and third elements, and unpack fruit2 and fruit4.
We can also combine _
and *
:
_, fruit2, *_ = fruits
print(fruit2) # Banana
Here _
ignores the first element, fruit2 unpacks the second element, and _*
collects the remaining elements and discards them.
We can also use multiple _
variables:
_, _, fruit3, _ = fruits
print(fruit3) # Cherry
Here we ignore the first 2 elements using _
, unpack fruit3, and ignore the last element.
So in summary:
_
variable ignores an element during list unpacking*
collects remaining elements, but then discards themWe can use multiple
_
variables to ignore multiple elementsWe can combine
_
and*
to ignore the first few elements and collect the rest
This allows us to unpack only the elements we are interested in, while ignoring the rest.
Disclaim: This article was created by Rix AI assistance. For now this is good enaugh to understand the List collection. We will encouter the list in many examples after we learn about other collections and composite data types in Python.