List & Tuple
F4 Python Lesson 3
What is List?
• List is a kind of sequence data structure.
• data is stored following an order.
Pair of square brackets [ ]
numbers = [1, 2, 3, 4, 5]
Values inside the list
# It takes 3 variables to
store all data
num_1 = 3
num_2 = 5
num_3 = 7
# It only takes one list to
store them
numbers = [3, 5, 7]
What is List?
• This data structure can store any type of value.
• It can be extended to store as much as it needs.
a = []
# Empty list
b = [1, 2, 3]
# Number list
c = ["Mary", 20, 24536.5]
# Personal info
d = [True, False, False, False, True] # MCQ answer
e = list(range(10))
# list created from range()
Access Element in List
• We do indexing to access the specific position of list.
• If the length of list is N, then the index counts from 0, up to N-1.
numbers = [2, 4, 6, 8, 10]
N = len(numbers)
# len() to get list length
print(numbers[0])
# position 0: 2
print(numbers[2])
# position 2: 6
print(numbers[N-1]) # position 4: 10
numbers = [2, 4, 6, 8, 10]
N = len(numbers)
print(numbers[0])
# position 0: 2
print(numbers[2])
# position 2: 6
print(numbers[N-1]) # position 4: 10
Access Element in List
N=5
numbers[0]
… …
numbers[4]
numbers
2
4
6
8
10
…
index
0
1
2
3
4
…
Access Element in List
• We can change the value of that position by assigning to it directly.
• Be careful of the IndexError: list index out of range. It happens when you access
non-existent list element.
numbers = [2, 4, 6, 8, 10]
numbers[1] = 5
numbers[3] = 7
print(numbers)
# [2, 5, 6, 7, 10]
numbers[5] = 12
# IndexError!
Negative Indexing
• In Python, we can represent the list positions counting from backward.
numbers[-5]
… …
numbers[-1]
numbers
2
4
6
8
10
…
index
0
1
2
3
4
…
Negative
index
-5
-4
-3
-2
-1
Count from -1
Negative Indexing
• No matter the index is positive or negative, it is pointing to the same list.
• You must also be careful of the IndexError problem.
numbers = [2, 4, 6, 8, 10]
N = len(numbers)
print(numbers[-1])
# 10
print(numbers[-2])
# 8
print(numbers[-N])
# 2
print(numbers[-2] == numbers[3])
# True
print(numbers[-N-1])
# IndexError!
Submit the file
F4@##Ex3-1.py
to teacher.
Exercise 3-1
Mission:
• Follow the instruction and
complete the exercise.
Access List Element in For Loop
• Sometime we repeat accessing all list elements one by one.
• This action is called the iteration, where we went through the entire list.
students = ["Bob", "Tony", "Ray", "Leon"]
print("Hello", students[0])
print("Hello", students[1])
print("Hello", students[2])
print("Hello", students[3])
# Access all students
Access List Element in For Loop
• Normally we use for loop to achieve iteration.
• The variable defined within the for loop (namely i) will represent each element.
students = ["Bob", "Tony", "Ray", "Leon"]
print("Hello", students[0])
print("Hello", students[1])
print("Hello", students[2])
print("Hello", students[3])
students = ["Bob", "Tony", "Ray", "Leon"]
for i in range(len(students)):
print("Hello", students[i])
for i in range(len(L)) v.s. for i in L
We declare i for two purposes:
1. Use i as the index of list; where i ∈ [0, N − 1]
2. The i represents the element; so i ∈ 𝐿
students = ["Bob",
"Tony", "Ray", "Leon"]
range(len(List)) -> 0, 1, 2, …, n-1
for i in range(len(students)):
print("Hello", students[i])
for i in students:
print("Hello", i)
i becomes an index: 0, 1, 2, …, n-1
i becomes the element: "Bob", "Tony", …
for i in range(len(L))
• If we need the index and the element, then we use range() to create the index
sequence.
Steps
students = ["Bob", "Tony", "Ray", "Leon"]
N = len(students)
# The length of list
for i in range(N): # range(N) -> 0, 1, ..., N-1
print(f"Student {i+1}: {students[i]}")
N=len(students)=4
range(N)=0,1,2,3
i=0, students[0]="Bob"
i=1, students[1]="Tony"
i=2, students[2]="Ray"
i=3, students[3]="Leon"
for i in L
• Otherwise, we access the elements directly.
Steps
num_list = [1, 3, 6, 8]
total = 0
for i in num_list:
total = total + i
print(total)
# 18
total=0
i=1, total=0+1=1
i=3, total=1+3=4
i=6, total=4+6=10
i=8, total=10+8=18
Modifying List elements in For Loop
• When you modify the list, make sure to change the list directly, not the variable i
that copy values from the list!
numbers = [1, 3, 5, 7, 9]
for i in range(len(numbers)):
numbers[i] *= 2
print(numbers) # [2, 6, 10, 14, 18]
numbers = [1, 3, 5, 7, 9]
for i in numbers:
i *= 2
print(numbers) # [1, 3, 5, 7, 9]
i here is the copy of the list elements
Proper way to name i
i here is a default name of the for loop variable, which is optional to call it i. we
usually name them as follow, if they are:
• Index: i, j, k
• Elements: x, elem, or specific name (student, num, name, etc.)
num_list = [1, 3, 6, 8]
total = 0
N = len(num_list)
for i in range(len(N)):
total = total + num_list[i]
print(total)
# 18
num_list = [1, 3, 6, 8]
total = 0
for num in num_list:
total = total + num
print(total)
# 18
Submit the file
F4@##Ex3-2.py
to teacher.
Exercise 3-2
Mission:
• Follow the instruction to
complete the list iteration.
What is Tuple?
• Tuple is also a kind of sequence data structure.
• It is similar to list, but it is immutable.
Pair of parentheses ( )
numbers = (1, 2, 3, 4, 5)
Values inside the list
What is Tuple?
• Immutable means it cannot be changed after declaration.
• However, we can still access data inside the tuple like how we access a list.
numbers = (1, 2, 3)
print(numbers[0])
# 1
print(numbers[-1]) # 3
numbers = (1, 2, 3)
for i in range(len(numbers)):
print("Number:", numbers[i])
numbers[1] = -1
# TypeError: 'tuple' object does
not support item assignment
total = 0
for num in numbers:
total += num
print(total)
# 6
What is Tuple?
• It is usually used for passing temporary data.
• For example, when a function has multiple return value, it is actually returning a
tuple.
def func():
return 1, 2, 3
x = func()
print(x)
print(type(x))
# (1, 2, 3)
# <class 'tuple'>
Unpacking Sequences
• Sequences, including list and tuple, can be unpacked by simply assigning to
variables.
• However, the number of variables must match the number of values unpacked.
x = (1, 2, 3)
a, b, c = x
x = (1, 2, 3)
a, b = x
# ValueError: too many values to
unpack (expected 2)
# a=1, b=2, c=3
x = (1, 2, 3)
a, b, c, d = x
# ValueError: not enough values to
unpack (expected 3, got 2)
List Operations
F4 Python Lesson 3
List operation
g
a
b
a
c
d
e
Update
c
d
e
a
b
c
d
f
e
f
Add
d
Search
b
a
b
c
d
a
e
Delete
b
c
d
e
a
c
d
e
g
Update Items
a
• We can change the value of that position by assigning to it directly.
x = ["a", "b", "c", "d", "e"]
x[2] = "g"
x[-1] = "h"
# c -> g
# e -> h
b
c
d
e
Search Items
d
• We can check if the item is in our list.
• index() will return the first matched element’s index.
x = ["a", "b", "c", "d", "e"]
print("a" in x)
print("f" in x)
# True
# False
idx = x.index("d")
# 3
a
b
c
d
e
a
Add Items
b
c
d
e
a
b
c
d
f
e
• We can append a new item at the end of the list;
• Or, insert a item into specific position;
• Or, combine two lists and create a new one using + operator.
x = ["a", "b", "c", "d", "e"]
x = ["a", "b", "c", "d", "e"]
x.append("f")
# ['a', 'b', 'c', 'd', 'e', 'f']
y = [1, 2, 3]
x = x + y
x.insert(1, "o")
# ['a', 'o', 'b', 'c', 'd', 'e', 'f']
print(x)
# ['a', 'b', 'c', 'd', 'e', 1, 2, 3]
f
a
Delete Items
b
c
d
e
a
c
d
e
• We can pop the last item out of the list (and get its value);
• We can also match and remove an item by its values.
• To remove safely, we can first do an existence check.
x = ["a", "b", "c", "d", "e"]
x = ["a", "b", "d", "b", "d"]
x.pop()
# pop 'e'
x.remove("b")
# ['a', 'd', 'b', 'd']
elem = x.pop()
elem2 = x.pop(1)
# pop 'd'
# pop 'b'
x.remove("A")
# ValueError!
print(x)
# ['a', 'c']
if "A" in x:
# existence check
x.remove("A")
Submit the file
F4@##Ex3-3.py
to teacher.
Exercise 3-3
Mission:
• Follow the instruction to
complete the list operations.
Submit the file
F4@##Ex3-4.py
to teacher.
Exercise 3-4
Mission:
• You are the manager of a
fruit store.
• Apply list operations and
list iterations to maintain
your products.