L5: Operations with Lists, Tuples

Bogdan G. Popescu

John Cabot University

Introduction

We previously covered lists

It is important to mention that lists are mutable. They are different from immutable objects.

  • Mutable Types

    • Objects that can be modified after creation.
    • Examples: list, dict, set
  • Immutable Types

    • Objects that cannot be changed after creation.
    • Examples: int, float, str, tuple

List Operations

Finding an element in a list

If you want to find the position of an element is a list, we can use the index() function

list_students = ["John", "Anna", "Emma"]
print(list_students.index('John'))
0
list_students = ["John", "Anna", "Emma"]
print(list_students.index('Anna'))
1
list_students = ["John", "Anna", "Emma"]
print(list_students.index('Emma'))
2

List Operations

Testing if an item is in a list

We can also test if certain words are within a list

list_students = ["John", "Anna", "Emma"]
print("Emma" in list_students)
True
print("Tom" in list_students)
False

List Operations

Appending items to the end of 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.

list_students = ["John", "Anna", "Emma"]
list_students.append("Tom")
print(list_students)
['John', 'Anna', 'Emma', 'Tom']

List Operations

Appending items inside 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.

list_students = ["John", "Anna", "Emma"]
list_students.insert(1, 'Tom')
print(list_students)
['John', 'Tom', 'Anna', 'Emma']

List Operations

Creating an empty list and appending

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

list_students = []
list_students.append("John")
list_students.append("Anna")
list_students.append("Emma")
print(list_students)
['John', 'Anna', 'Emma']

List Operations

Sorting a List

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']

List Operations

Sorting a numerical list

We can also sort a numerical list

numbers = [1, 3, 4, 2]
numbers.sort()
print(numbers)
[1, 2, 3, 4]

List Operations

Finding the length (size) of a list

This is how we find how many items we have in our list

list_students = ["John", "Anna", "Emma"]
no_students = len(list_students)
no_students
3

We can make statements about this number.

print("There are " + str(no_students) + " students in the list made out of "+ str(list_students))
There are 3 students in the list made out of ['John', 'Anna', 'Emma']

List Operations

Making statements about list elements

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”

List Operations

Making statements about list elements

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].

List Operations

Exercises 1

Working with lists:

  1. Make a list that includes four animals such as: “bear”, “cat”, “dog”, etc.
  2. Use the list.index() function to find the index of one animal in your list.
  3. Use the in function to show that this animal is in your list.
  4. Use the append() function to add a new career to your list.
  5. Use the insert() function to add a new career at the beginning of the list.
  6. Use a loop to show all the careers in your list.

List Operations

Exercises 1

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)

List Operations

Exercises 1

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

List Operations

Exercise 2

Working with lists

  1. Create a list but this time start your file with an empty list and fill it up using append() statements.
  2. Print a statement that tells us what the first animal in your list is.
  3. Print a statement that tells us what the last animal in your list is.

List Operations

Exercise 2

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

List Operations

Removing items from a list: by value

We can easily remove items from a list by values.

#Step 1: list
animals = ["bear", "cat", "dog", "elephant"]
animals.remove('bear')
print(animals)
['cat', 'dog', 'elephant']

List Operations

Removing items from a list: by position

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']
print("Removed item:", removed_item)
Removed item: cat

List Operations

List Slicing

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.

animals = ["bear", "cat", "dog", "elephant"]

animals_sliced_list = animals[0:2]
animals_sliced_list
['bear', 'cat']

Another option is to slice all items up to a certain position.

animals = ["bear", "cat", "dog", "elephant"]

animals_sliced_list = animals[:2]
animals_sliced_list
['bear', 'cat']

List Operations

The range() function

The range() is helpful if we want to work with a set of numbers.

It helps us generate lists of numbers.

# Print the first ten numbers.
for number in range(1,5):
    print(number)
1
2
3
4

We can also indicate how big the step between numbers should be:

# Print the first ten odd numbers.
for number in range(1,6,2):
    print(number)
1
3
5

We can easily create a list out of that range in the following way:

numbers = list(range(1,5))
print(numbers)
[1, 2, 3, 4]

List Operations

The min(), max(), and sum() functions

There are three functions that work with numerical lists: min(), max(), and sum()

ages = [10, 12, 14, 6]

youngest = min(ages)
oldest = max(ages)
total_years = sum(ages)

print("Our youngest member is " + str(youngest) + " years old.")
Our youngest member is 6 years old.
print("Our oldest member is " + str(oldest) + " years old.")
Our oldest member is 14 years old.
print("Together, they have " + str(total_years) + " years worth of life experience.")
Together, they have 42 years worth of life experience.

List Operations

Exercise

Imagine five jars with different amounts of candies in them. Store these five values in a list, and print out the following sentences:

  1. “The jar with the most candies has X candies.”
  2. “The jar with the least candies has X candies.”
  3. “Altogether, these jars have X candies.”

List Operations

Exercise Solution

# 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 Operations

List Comprehensions

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

# Store the first ten square numbers in a list.
# Make an empty list that will hold our square numbers.
squares = []

# Go through the first ten numbers, square them, and add them to our list.
for number in range(1,5):
    squares.append(number**2)
    
# Show that our list is correct.
squares
[1, 4, 9, 16]

List Operations

List Comprehensions

We can however achieve the same result using:

# Store the first ten square numbers in a list.
squares = [number**2 for number in range(1,5)]
squares
[1, 4, 9, 16]

List Operations

List Comprehensions

Let us go over another example in which we multiply by 2.

multiplication = []

for number in range(1,5):
    multiplication.append(number*2)
  
multiplication  
[2, 4, 6, 8]

List Operations

List Comprehensions

Let us now do the same thing using list comprehensions

multiplication = [number*2 for number in range(1,5)]
multiplication
[2, 4, 6, 8]

List Operations

Non-numerical 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.

list_students = ["John", "Anna", "Emma"]

for student in list_students:
  print(student + " is a student in this class.")
John is a student in this class.
Anna is a student in this class.
Emma is a student in this class.

List Operations

Non-numerical comprehensions

We can obtain the same outcome in the following way:

list_students = ["John", "Anna", "Emma"]

list_students_sentences = [student + " is a student in this class." for student in list_students]

for sentence in list_students_sentences:
  print(sentence)
John is a student in this class.
Anna is a student in this class.
Emma is a student in this class.

Tuples

Introduction

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:

  • the values of the elements of a tuple cannot be modified (they are immutable)
  • parantheses are used instead of square brackets

Tuples

Introduction

This is how we can create a tuple

mytuple1 = tuple()
mytuple2 = ()
mytuple3 = (1, 'a', 71.4)
mytuple4 = 1, 'a', 71.4

Similar to lists, we can extract the elements of a tuple in the following way:

mytuple4[0]
1

But we cannot change the elements (“immutable”). The following will yiled an error:

mytuple4[0] = 5

Tuples

Operations with Tuples

We can concatenate two tuples in the following way:

mytuple3 + mytuple4