0
We previously covered lists
It is important to mention that lists are mutable. They are different from immutable objects.
Mutable Types
list
, dict
, set
Immutable Types
int
, float
, str
, tuple
If you want to find the position of an element is a list, we can use the index() function
We can also test if certain words are within a list
We can easily add items to a list by using the append
method.
This method adds the new item to the end of a list.
We can easily add items to a list by using the insert
method.
This method adds the new item at a specified position.
We can also start with an empty list and add to that list dynamically.
Here is for example how we can add to a list iteratively
We can easily sort a list in python in the following way
list_students = ["John", "Anna", "Emma"]
#Alphabetical order
list_students_sorted = sorted(list_students)
print(list_students_sorted)
['Anna', 'Emma', 'John']
#Reverse alphabetical order
list_students_sorted_reverse = sorted(list_students, reverse=True)
print(list_students_sorted_reverse)
['John', 'Emma', 'Anna']
We can also sort a numerical list
This is how we find how many items we have in our list
We can make statements about this number.
We can also make statements about the elements in the list in the following way:
list_students = ["John", "Anna", "Emma"]
print("In the exam %s will go first, followed by %s, and %s." % (list_students[0], list_students[1], list_students[2]))
In the exam John will go first, followed by Anna, and Emma.
Notice here the %s
is called a placeholder.
In the print()
function, the text includes %s
three times.
Each %s
serves as a placeholder where a string value will be inserted later.
After the string, we add a tuple (list_students[0], list_students[1], list_students[2])
.
These represent the first, second, and third elements of the list, which are the names “John”, “Anna”, and “Emma”
We can also make statements about the elements in the list in the following way:
list_students = ["John", "Anna", "Emma"]
print("In the exam %s will go first, followed by %s, and %s." % (list_students[0], list_students[1], list_students[2]))
In the exam John will go first, followed by Anna, and Emma.
The %s
placeholders will be replaced with these values in the same order. So %s
will take the value of list_students[0]
, then list_students[1]
, and finally list_students[2]
.
Working with lists:
list.index()
function to find the index of one animal in your list.in
function to show that this animal is in your list.append()
function to add a new career to your list.insert()
function to add a new career at the beginning of the list.Working with lists: solution
#Step 1: list
animals = ["bear", "cat", "dog", "elephant"]
#Step2: using list.index()
index_of_cat = animals.index("cat")
print(f"Index of 'cat': {index_of_cat}")
#Step3: Using the `in` function
is_cat_in_list = "cat" in animals
print(f"Is 'cat' in the list? {is_cat_in_list}")
# Step 4: Use the `append()` function to add a new career to your list
animals.append("lion")
print("List after appending 'lion':", animals)
# Step 5: Use the `insert()` function to add a new career at the beginning of the list
animals.insert(0, "tiger")
print("List after inserting 'tiger' at the beginning:", animals)
# Step 6: Use a loop to show all the careers in your list
print("All animals in the list:")
for animal in animals:
print(animal)
Working with lists: solution
Index of 'cat': 1
Is 'cat' in the list? True
List after appending 'lion': ['bear', 'cat', 'dog', 'elephant', 'lion']
List after inserting 'tiger' at the beginning: ['tiger', 'bear', 'cat', 'dog', 'elephant', 'lion']
All animals in the list:
tiger
bear
cat
dog
elephant
lion
Working with lists
Working with lists
# Step 1: Create an empty list and fill it up using append() statements
animals = []
animals.append("bear")
animals.append("cat")
animals.append("dog")
animals.append("elephant")
# Step 2: Print a statement that tells us what the first animal in your list is
first_animal = animals[0]
print(f"The first animal in the list is: {first_animal}")
The first animal in the list is: bear
# Step 3: Print a statement that tells us what the last animal in your list is
last_animal = animals[-1]
print(f"The last animal in the list is: {last_animal}")
The last animal in the list is: elephant
We can easily remove items from a list by values.
We can also remove items by position
animals = ["bear", "cat", "dog", "elephant"]
# Finding the index of "cat"
index_of_cat = animals.index("cat")
# Removing "cat" from the list
animals2 = animals.copy() # Make a copy of the list
removed_item = animals2.pop(index_of_cat)
print("Modified list:", animals2)
Modified list: ['bear', 'dog', 'elephant']
Removed item: cat
Since a list is a collection of items, we should be able to get any subset of those items.
For example, if we want to get just the first three items from the list, we should be able to do so easily.
['bear', 'cat']
Another option is to slice all items up to a certain position.
range()
functionThe range()
is helpful if we want to work with a set of numbers.
It helps us generate lists of numbers.
We can also indicate how big the step between numbers should be:
We can easily create a list out of that range in the following way:
min()
, max()
, and sum()
functionsThere are three functions that work with numerical lists: min()
, max()
, and sum()
Imagine five jars with different amounts of candies in them. Store these five values in a list, and print out the following sentences:
# List storing the number of candies in each jar
candies = [50, 30, 75, 20, 90]
# Finding the jar with the most candies
max_candies = max(candies)
print(f"The jar with the most candies has {max_candies} candies.")
# Finding the jar with the least candies
min_candies = min(candies)
print(f"The jar with the least candies has {min_candies} candies.")
# Calculating the total number of candies in all jars
total_candies = sum(candies)
print(f"Altogether, these jars have {total_candies} candies.")
The jar with the most candies has 90 candies.
The jar with the least candies has 20 candies.
Altogether, these jars have 265 candies.
List Comprehensions help us create and work with lists.
They are frequently used in programming.
So far we learned the following way of dealing with lists
We can however achieve the same result using:
Let us go over another example in which we multiply by 2.
Let us now do the same thing using list comprehensions
We can use comprehensions with non-numerical lists as well.
We will first create an initial list.
We will then use a comprehension to make a second list from the first one.
We can obtain the same outcome in the following way:
A tuple is a sequence of values, similar to a list.
The values stored in a tuple can be of any type and are indexed by intergers.
Tuples are different from lists:
This is how we can create a tuple
Similar to lists, we can extract the elements of a tuple in the following way:
But we cannot change the elements (“immutable”). The following will yiled an error:
We can concatenate two tuples in the following way:
Popescu (JCU): Lecture 5