You are on page 1of 23

Chapter 7.

Iterative data
types
Lecturer: Đinh Thị Hà
Email: dinhha100983@gmail.com
Mobile: 0947830983
Contents

• 7.1. List
• 7.2. Tuple
• 7.3. Dictionary
• 7.4. Set
• 7.5. Array
• 7.6. Convert among iterative data types
7.1. List

• 7.1.1. Concept và characteristics

• 7.1.2. Access list

• 7.1.3. Methods

• 7.1.4. List of list


7.1.1. Concept and characteristics

• Concept: Lists are one of 4 built-in data types in Python used to store
collections of data. It is used to store multiple items in a single variable.
• Create a list:
• Syntax: Var_name=[list of values]
Or use the constructor method list()
Var_name=list(list of values)
• Examples:
L1=[1, 5, 8]
L=list(“math”, “physics”, “chemistry”)
• Features/characteristics:
• List items are indexed, ordered, changeable, and allow duplicate values, items can be of
any data type.
• A list can contain different data types
• Items in a list are indexed begin with 0
7.1.2. Access list

• To access an element/item of a list, use/refer the index number of item


and slicing operations along with operator [].
• To get the length of a list, len() function is used.
• Examples:
L2=[“math”, “physics”,”chemistry”]
L3=[“abc”, 12, 12, True]
Print(len(L3))
Print(L2[1])
7.1.2. Access list

• Notes: items in a list are indexed begin with 0 and Negative indexing means start from
the end.
List = [12, ‘learning’, 3, ‘Python’, 5]
print("Accessing element using negative indexing")
# print the last element of list
print(List[-1])
# print the third last element of list
print(List[-3])
#####
L2=[“toan”, “ly”,”hoa”, “van”,”su”, “dia”]
Print(L2[1])
Print(L2[-1]) #dia
Print(L2[-2]) #su
7.1.2. Access list

• It is possible to access a range of items from a list basing on slice


operation with colon (:).
Print(L2[2:5]) # ”hoa”, “van”, ”su”
Print(L2[-5:-2]) #kết quả???
Print(L2[:4])
Print(L2[2:])
• It is possible to add , remove element, concate/combine two lists
L2.append(“literature”) # add an item at the end of list
L2.insert(2,”biology”) # add an item into the third position of the list.
L2. extend(L3) # concate L3 into the end of L2
L=L2+L3 #concate two list L2 and L3
7.1.2. Access list

• To determine if a specified item is present in a tuple use the ”in” operator/ keyword: .
If “sinh” in L2:
Print(“mon ’sinh’ co trong L2”)
• To go through items in a list, use for loop along with “in” operator or refer to the
index of item with range() function or use while loop along with len() function .
Ls=[“toan”, “ly”,”hoa”, “van”,”su”, “dia”]
For x in Ls:
Print(x)

For i in range(len(Ls)):
Print(Ls[i])

i=0
While i<len(Ls):
Print(Ls[i])
i=i+1
7.1.4. List of list
• List of list / nested list allow create a list in which each item in the list is also another list.
• Examples:
matrix = [[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]]
• Or:
matrix = []
for i in range(5):
# Append an empty sublist inside the list
matrix.append([])
for j in range(5):
matrix[i].append(j)
print(matrix)
• Or:
matrix = [[j for j in range(5)] for i in range(5)]
print(matrix)
7.1.4. List of list

• Examples:
matrix = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
flatten_matrix = []
for sublist in matrix:
for val in sublist:
flatten_matrix.append(val)
print(flatten_matrix)

• Or:
matrix = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
# Nested List Comprehension to flatten a given 2-D matrix
flatten_matrix = [val for sublist in matrix for val in sublist]
print(flatten_matrix)
7.1.3. Methods
Practice exercises

1. Write a program that asks the user to enter a list of integers. Do the
following:
(a) Print the total number of items in the list.
(b) Print the last item in the list.
(c) Print the list in reverse order.
(d) Print Yes if the list contains a 5 and No otherwise.
(e) Print the number of fives in the list.
(f) Remove the first and last items from the list, sort the remaining items, and print
the result
(g) Print how many integers in the list are less than 5.
Practice exercises

2. Write a program that generates a list of 20 random numbers between 1


and 100.
(a) Print the list.
(b) Print the average of the elements in the list.
(c) Print the largest and smallest values in the list.
(d) Print the second largest and second smallest entries in the list
(e) Print how many even numbers are in the list
Practice exercises

3. Start with the list [8,9,10]. Do the following:


(a) Set the second entry (index 1) to 17
(b) Add 4, 5, and 6 to the end of the list
(c) Remove the first entry from the list
(d) Sort the list
(e) Double the list
(f) Insert 25 at index 3 The final list should equal [4,5,6,25,10,17,4,5,6,10,17]
7.2. Tuple

• 7.2.1. Concept và characteristics

• 7.2.2. Access tuple


• 7.2.3. Methods
7.2.1. Concept và characteristics

• Concept: A tuple is a sequence of immutable objects. Tuples are used to


store multiple items in a single variable.
• Syntax: Var_name=(list of items)
• Or use the constructor method tuple – a built-in function
• Examples:
T=(“An”, “Cường”, “Linh”)
T=tuple((2,5,8))
• Note: If the tuple has only 1 item, there must be a comma after the item to
identify the type of the tuple, otherwise it will understand the type of the
item.
• T=(“An”,); T2=(“An”), T3=(4)
Print(type(T)); print (type(T2)); print(type(T3))
7.2.1. Concept và characteristics/features

• Features/Characteristics (is quite the same as list):


• List items are indexed, ordered, unchangeable, and allow duplicate values, items
can be of any data type.
• A tuple can contain different data types.
• Cannot change, add or remove items after the tuple has been created.
• Examples:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple1 = ("abc", 34, True, 40, "male")
7.2.1. Concept và characteristics/features

• Notes: Tuples are unchangeable, meaning that you cannot change, add, or remove items
once the tuple is created.
• Solutions/ workarounds:
• convert the tuple into a list, change the list (by add or remove items), and convert the list
back into a tuple.
• Or add tuple to tuple by + operator
• Ví dụ:
T=(“Apple”, “Grape”, “Mango”)
L=list(T) ; #convert tuple into a list
L[1]=“Cherry”; L.append(“Lemon”); L.pop(2) #change the list
T=tuple(L) #convert the list into a tuple
Print(T)

thistuple = ("apple", "banana", "cherry"); y = ("orange",)


thistuple += y
print(thistuple)
7.2.2. Access tuple
• To access an element/item of a list, use/refer the index number and slicing
operations along with operator [].
• Items in a list are indexed begin with 0, Negative indexing means start
from the end.
• It is possible to access a range of items from a list basing on slice
operation with colon (:).
• To determine if a specified item is present in a tuple use the in keyword:
• To get the number of items in a tuple, use len() function.
• To go through items in a list, use for loop along with “in” operator or
refer to the index of item with range function or while loop along with len
function.
7.2.2. Access tuple

• Examples:
• tup = ("apple", "banana", "cherry", "orange", "kiwi")
print(tup[1]); print(tup[-1])
• print(tup[2:4]); print(tup[:4]); print(tup[2:])
• if "apple" in tup:
print("Yes, 'apple' is in the fruits tuple")
• for x in tup:
print(x)
• for i in range(len(tup)):
print(tup[i])
7.2.2. Access tuple
• Packing/Unpacking a Tuple
• " packing" a tuple: When creating a tuple and assigning values to it.
• "unpacking": extract the values in a tuple back into variables
• Examples:
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
• Can use asterisk (*) to replace a part of a tuple (some of items) to match with
some of the variables corresponding
• Example:
T=(“Math”, “Physics”, ”Chemistry”, “Biology”, “History”)
(to,*ph, su)=T
Print(to);print(ph); print(su) #Math [‘Physics’, ‘Chemistry’, ‘Biology’] History
7.2.3. Methods
THANK YOU

You might also like