Lecture 1
Lecture 1
Sequences
List and Tuples
Russel L. Villacarlos
College of Engineering and Instructor / Professor
Information Technology
Sequence
• A list can also be created from existing iterables using the list
type constructor
• Ex: r = list(range(5))
• Ex: r = tuple(range(5))
⋮
else:
College of Engineering and print(rating[0])
Information Technology
Tuple Use Cases
def top3(l):
return tuple(sorted(l)[:-3])
index = 0
for e in emp:
• It is sometimes necessary to print(index,": ",e, sep="")
keep track of a counter each index = index + 1
zip
• This is also known as matrix
transpose
John Male 25
Kath Female 23
Claire Female 24
College of Engineering and
Information Technology
zip() function
#Original matrix
• Given z, the iterable created nums1 = [[1,2],[3,4],[5,6]]
from zip(), the original #Transposed: list of tuples
iterables can be #[(1,3,5), (2,4,6)]
reconstructed by applying nums1_t = [*zip(*nums)]
zip
iterables can be
reconstructed by applying
zip()to *z 1 3 5
2 4 6
zip
iterables will not be retained
• The iterables must be 1 2
converted to the original type 3 4
College of Engineering and 5 6
Information Technology
zip() function
def get_age(emp):
return emp[1]
• Both the sort() and sorted()
functions have two optional def get_gender(emp):
named parameters return emp[2]
• key
emp = [("John", 25, "Male"),
• reverse ("Kath", 23, "Female"),
("Claire",24,"Female")]
• The argument to key is a
print("Original: ",emp)
function that takes only one print("Sorted: ", sorted(emp))
input print("Sorted by name: ",
• The function is applied to each sorted(emp,key=get_name))
element of the iterable to be print("Sorted by age: ",
sorted sorted(emp,key=get_age))
• The output of the function is used print("Sorted by gender: ",
College ofas basis for comparison
Engineering and sorted(emp,key=get_gender))
Information Technology
sorted()
def get_age(emp):
return emp[1]
• The argument to reverse is a
Boolean value emp = [("John", 25, "Male"),
• It is False by default ("Kath", 23, "Female"),
("Claire",24,"Female")]
• If set to True, the result will be
in reversed order print("Original: ",emp)
print("Sorted: ", sorted(emp))
print("Sorted by age: ",
sorted(emp,key=get_age))
print("Sorted by age (reversed): ",
sorted(emp,key=get_age,reverse=True))