numbers = [10, 5, 7, 2, 1]Intro on Lists
Why use lists?
When you need to read, store, process, and print large amounts of numbers, creating a separate variable for each one is impractical. For instance, reading five numbers individually would be cumbersome and time-consuming.
var1 = 10
var2 = 5
var3 = 7
var4 = 2
var5 = 1Creating a list
A list is a table of values, allowing a program to store multiple values inside a single variable.
Example
This creates a list named numbers containing five values. List is a special variable, which can hold more than one value at a time. Using lists makes it convenient to manage and process large sets of data, such as sorting numbers in ascending order. This approach simplifies code and improves readability.
Heterogenous lists
The elements inside a list may have different types. Some of them may be integers, others floats, and yet others may be lists.
Example
magic_bag = [True, 1, 5, "orange", 55.89]
print(f"Here's a bag of stuff: {magic_bag}")Here's a bag of stuff: [True, 1, 5, 'orange', 55.89]
Altough possible, using a heterogenouse list (mixing elements of different data types) is not recommended. As you’ll discover later, lists can be used to calculate statistics or rearranged in specific order. These functionalities will fail if the values aren’t of the same type!
Empty List
You may also create a list without any values. This can be useful if the values are added later during the program execution. You can add element using append() as described later in this lesson.
my_list = []The length of list
The length of a list, i.e the number of elements it contains, can change during program execution as new elements are added or existing elements are removed. This makes lists very dynamic.
To check the current length of a list, you can use the len() function, which takes the list’s name as an argument and returns the number of elements currently in the list.
Example:
The sum of elements
The sum of all elements in a list might be very useful for computing averages or accumulated totals.
To get the sum simply call the function sum() and pass the list as argument.
Example
Example
To calculate the average value, you can use both sum() and len() as such:
The extrema (min/max)
The smallest and largest value in a list can be obtained with min() and max() which are also built-in python functions.
Example: Min/Max
Adding elements to a list: append()
append()
A new element may be added to the end of the existing list:
Example
numbers = [1,2,3]
numbers.append(4) # Will add 4 at the end of the list
print(numbers)[1, 2, 3, 4]
Example with loops
The .append() method can also be called within a loop:
numbers = [1,2,3]
for i in range(10):
numbers.append(4) # Will add 4 at the end of the list 10 times
print(numbers)[1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
List methods
insert()
The insert() method is also for adding elements but is a bit smarter ‒ it can add a new element at any place in the list, not only at the end.
Example:
The append() method in Python adds an element to the end of a list, while the insert() method inserts an element at a specified position, shifting subsequent elements to the right. The len() function returns the number of elements in the list.
Pay attention to what happens after using insert(): the former first element is now the second, the second the third, and so on.
pop()
An element may be removed from the list at a specific position using the pop() method:
How It Works:
- The list’s length decreases by one after the operation.
- Attempting to
pop()an index that doesn’t exist raises anIndexError.
Example:
Summary
| Operation | Example | Result |
|---|---|---|
| Create an empty list | a = [] | a is [] |
| Create a list | a = [1,2,3,3] | a is [1,2,3,3] |
| Access item | a[0] | 1 |
| Change item | a[1] = 10 | a is [1,10,3,3] |
| Add item | a.append(5) | a is [1,10,3,3,5] |
| Add Item | a.insert(2,88) | a is [1,10,88,3,3,5] |
| Remove first occurrence | a.remove(3) | a is [1,10,88,3,5] |
| Remove last item | a.pop() | a is [1,10,88,3], returns 5 |
| Remove item by index | a.pop(0) | a is [10,88,3], returns 1 |
| Count items | len(a) | 3 |