Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

DCIT 23: Computer Programming 2

Sequences
List and Tuples

Russel L. Villacarlos
College of Engineering and Instructor / Professor
Information Technology
Sequence

• A sequence is an ordered collection where an element in the


collection is identified by its position called index
• Elements need not be unique

• Some of the common sequence types in Python are string, list,


range, and tuple

• Sequences can be mutable or immutable


• String, range and tuple are immutable
• List is mutable

• Sequences are iterable


College of Engineering and
Information Technology
Common Sequence Operations
Operation Description
x in s Tests if x is an element of the sequence s
x not in s Tests if x is not an element of the sequence s
s1 + s2 Creates a new sequence containing the concatenation of s1 followed by
elements of s2
s * n Create a new sequence with s repeated n times
s[i] Returns the ith element in the sequence
s[i:j] The slice of sequence s. It returns the elements from index i to index j-1

College of Engineering and


Information Technology
Common Sequence Operations
Operation Description
s[i:j:k] Returns the elemts from index i to index j-1 with step k
len(s) Returns the length of the sequence s
min(s) Returns the smallest element in the sequence
max(s) Returns the largest element in the sequence
s.index(x,[i,[j]]) Returns position of x in the sequence, optionally restricting to the
range from i to j – 1
s.count(x) Returns the number of occurrences of x in the sequence

College of Engineering and


Information Technology
Mutable Sequence Operations
Operation Description
s[i] = x Replace element i by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
del s[i:j] Removes elements from slice of s. Same as s[i:j] = []
s[i:j:k] = t The elements of s[i:j:k] are replaced by those of iterable t
del s[i:j:k] Removes the elements of s[i:j:k] from the list
s.append(x) Appends x to the end of the sequence (same as s[len(s):len(s)] = [x])
s.clear() Removes all items from s (same as del s[:])
Creates a shallow copy of s (same as s[:])
s.copy()
A shallow copy is a new sequence, but the elements are aliases of
the elements in s
College of Engineering and
Information Technology
Mutable Sequence Operations
Operation Description
Extends s with the contents of iterable t (for the most part
s.extend(t) / s += t
the same as s[len(s):len(s)] = t)
s *= n Updates s with its contents repeated n times
s.insert(i, x) Inserts x into s at the index given by i (same as s[i:i] = [x])
s.pop([i] Retrieves the item at i and also removes it from s
s.remove(x) Remove the first item from s where s[i] is equal to x
s.reverse() Reverses the items of s in place

College of Engineering and


Information Technology
List

• List is a mutable sequence of elements


• Ex: emptyList = []
• Ex: subjects = ['DCIT 23']
• Ex: grades = [1.00, 1.25, 1.00, 3.00, 4.00. 2.50]
• Ex: persons = ['John', 'Claire', 'Olivia', 'Dylan', 'Kath']

• A list can be created either by:


• Bracket notation: ['a',1, True]
• Comprehension: [x for x in "hello world" if x in 'aeiou']

• List supports all common and mutable sequence operations


with the addition of the sort() method
College of Engineering and
Information Technology
List

• A list can also be created from existing iterables using the list
type constructor

• Ex: r = list(range(5))

• Ex: s = list("DCIT 23")

• Ex: l = list([1.00, 2.50, 1.25, 1.25])

College of Engineering and


Information Technology
Multidimensional List

• A list can be nested to create mat = [[1,2,3],


multidimensional list [4,5,6],
[7,8,9]]

• A 2-dimensional (2D) list is


for row in mat:
also called a matrix
for col in row:
print(col, end=" ")
print()

College of Engineering and


Information Technology
Multidimensional List

• A list can be nested to create rows = int(input("Rows:"))


multidimensional list cols = int(input("Cols:"))
mat = [[0 for c in range(cols)]
for r in range(rows)]
• A 2-dimensional (2D) list is
also called a matrix
for row in mat:
for col in row:
print(col, end=" ")
print()

College of Engineering and


Information Technology
Tuple

• Tuple is an immutable sequence of elements


• emptyTuple = ()
• subjects = ("DCIT 23",)
• grades = (1.00, 1.25, 1.00, 3.00, 2.50)
• employeeInfo = "John", 25, "Male", 1.63, 50

• A tuple can be created by simply listing the comma separated


elements
• Parenthesis are not required except when creating an empty tuple
• Trailing comma is needed when creating a single element tuple

• Tuple supports all common sequence operations

College of Engineering and


Information Technology
Tuple

• A tuple can also be created from existing iterables using the


tuple type constructor

• Ex: r = tuple(range(5))

• Ex: s = tuple("DCIT 23")

• Ex: l = tuple([1.00, 2.50, 1.25, 1.25])

College of Engineering and


Information Technology
Tuple Use Cases
Record
• By convention, list are used for
storing homogenous group of
data while tuples are for emp1 = ("John", 25, "Male")
heterogenous group of data
• This is not a hard rule in Python emp2 = ("Kath", 23, "Female")
emp3 = ("Claire",24,"Female")
• Tuples can be used to represent
a record
Name Age Sex
• A record is a collection of data
of different types called fields Fields

College of Engineering and


Information Technology
Tuple Use Cases

• By convention, list are used for


storing homogenous group of
data while tuples are for emp = [("John", 25, "Male"),
heterogenous group of data
• This is not a hard rule in Python ("Kath", 23, "Female"),
("Claire",24,"Female")]
• Tuples can be used to represent
a record A list of tuples

• A record is a collection of data


of different types called fields
College of Engineering and
Information Technology
Tuple Use Cases

• Since tuples are immutable, rating = ('Poor',


they can be used for group of 'Fair',
'Satisfactory',
data that must not be 'Very Satisfactory',
changed throughout the 'Outstanding')
program score = int(input('Score: '))

if score >= 90:


• Tuples can maintain the print(rating[4])
elif score < 90 and score >= 85
integrity of data print(rating[3])


else:
College of Engineering and print(rating[0])
Information Technology
Tuple Use Cases

• Tuples are also commonly def minmax(l):


used when returning multiple return min(l), max(l)

values from a function #divmod is actually a built-in function


def divmod(a,b):
return a//b, a % b

def top3(l):
return tuple(sorted(l)[:-3])

College of Engineering and


Information Technology
Packing and Unpacking

• Packing is the process of e1,e2,e3 = ['John','Claire','Olivia']


combining several data into a
name,age,sex = ('John', 25, 'Male')
collection like list and tuple
n1,n2,n3,n4 = range(3,7)

• Unpacking is the process of a,e,i,o,u = "aeiou"

laying-out the content of a #ValueError: Too many values to unpack


collection as individual items a,b,c = minmax([1,10,19,23,45])

#ValueError: Too many values to unpack


name,age = ('John', 25, 'Male')

College of Engineering and


Information Technology
Packing and Unpacking

• Elements of a collection can e1,e2,e3 = ['John','Claire','Olivia']


be unpacked into several
name,age,sex = ('John', 25, 'Male')
variables
• This is similar to single line n1,n2,n3,n4 = range(3,7)
multiple assignment
a,e,i,o,u = "aeiou"
• The number of elements in the
collection and the number of #ValueError: Too many values to unpack
variables must match, a,b,c = minmax([1,10,19,23,45])
otherwise a ValueError will be
#ValueError: Too many values to unpack
raised name,age = ('John', 25, 'Male')

College of Engineering and


Information Technology
Packing and Unpacking

• If only selected elements #Get the first two elements


must be assigned to e1, e2, *e = ['John','Claire','Olivia',
'Dylan', 'Kath']
individual variables, the
remaining elements can be #Get the last two elements
*e, e1, e2 = ['John','Claire','Olivia',
assigned to a variable 'Dylan', 'Kath']
prepended with an asterisk
#Get the first and last elements
e1, *e, e2 = ['John','Claire','Olivia',
'Dylan', 'Kath']

College of Engineering and


Information Technology
Packing and Unpacking

• A collection s can also be emp1 = ['John', 'Kath', 'Olivia']


unpacked inside a new
#Unpack emp1 inside emp2
collection by appending an emp2 = ['Claire', *emp1 ,'Dylan']
asterisk to s
#Store emp1 inside emp2
emp3 = ['Claire', emp1 ,'Dylan']

• This is different from storing #Unpacking ranges and string


the collection as element of r = (*range(5),*range(10,15))
another collection vowels = (*'aeiou',)

College of Engineering and


Information Technology
Packing and Unpacking

• A collection can also be emp = ['John', 'Kath', 'Olivia']


unpacked in a function call to
#Print input as a list
make each element an print(emp, sep = " | ")
argument to the function
#Unpack to input elements individually
print(*emp, sep = " | ")

College of Engineering and


Information Technology
enumerate() function

• Iterables are commonly emp = ['John','Claire','Olivia',


processed in a for loop 'Dylan', 'Kath']

index = 0
for e in emp:
• It is sometimes necessary to print(index,": ",e, sep="")
keep track of a counter each index = index + 1

time an element is processed


• Ex: The counter may represent
the index of an element in a
sequence

College of Engineering and


Information Technology
enumerate() function

• Python has a built in emp = ['John','Claire','Olivia',


enumerate() function that 'Dylan', 'Kath']

converts an iterable into a for index,e in enumerate(emp):


sequence of pairs (a 2- print(index,": ",e, sep="")
element tuple)
• The first element is the counter
assigned to the element of the
input tuple
• The second element is an
element of the input tuple

College of Engineering and


Information Technology
enumerate() function

• The starting value of the emp = ['John','Claire','Olivia',


counter can be set by passing 'Dylan', 'Kath']

a second argument to #Start the counter at 100


enumerate() for index,e in enumerate(emp,100):
print(index,": ",e, sep="")

College of Engineering and


Information Technology
zip() function

• The zip() function combines nums1 = [1,2,3,4]


multiple iterables to create an nums2 = [7,8,9,10]

iterable of tuples for n1,n2 in zip(nums1,nums2):


• The ith tuple contains the ith print(f'{n1} x {n2} = {n1*n2}')
element from each combined
iterable

• This allows parallel iteration


of the multiple iterables

College of Engineering and


Information Technology
zip() function

• If the iterables are viewed as emp = [['John', 'Kath', 'Claire']


rows of a matrix then zipping ['Male', 'Female', 'Female']
[25, 23, 24]]
them will convert them into
columns for e in zip(*emp):
print('Name: ',e[0])
print('Sex: ',e[1])
print('Age: ',e[2])
• This is also known as matrix
transpose

College of Engineering and


Information Technology
zip() function

• If the iterables are viewed as John Kath Claire


rows of a matrix then zipping Male Female Female
them will convert them into 25 23 24
columns

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

• When the input iterables have nums = [[1,2],[3,4,5],[6,7,8,9]]


varying lengths, zip() will
continue grouping until the #[(1,3,6), (2,4,7)]
print([*zip(*nums)])
shortest iterable is exhausted
#ValueError
print([*zip(*nums, strict = True)])
• The strict parameter can be
set to True to require the inputs
to have the same length
• A ValueError will be raised when
inputs have varying length

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()to *z #Transpose of the transposed


#Original matrix but tuples
#[(1,2), (3,4), (5,6)]
• The type of the original nums2 = [*zip(*nums1_t)]

iterables will not be retained #Transpose of the transposed


• The iterables must be #Converting to original type
#[[1,2], [3,4], [5,6]]
converted to the original type nums3 = [list(r) for r in zip(*nums1_t)]
College of Engineering and
Information Technology
zip() function
1 2
3 4
• Given z, the iterable created 5 6
from zip(), the original

zip
iterables can be
reconstructed by applying
zip()to *z 1 3 5
2 4 6

• The type of the original

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 unzip(z, ctype):


• Given z, the iterable created return [ctype(t) for t in zip(*z)]
from zip(), the original #Original matrix
iterables can be nums = [[1,2],[3,4],[5,6]]
reconstructed by applying
#transposed: list of tuples
zip()to *z #[(1,3,5), (2,4,6)]
nums_t = [*zip(*nums)]

• The type of the original #Reconstruct original from transposed


iterables will not be retained nums_r = unzip(nums1_t, list)
• The iterables must be
#Test if reconstructed equals original
converted to the original type print(nums_r == nums)
College of Engineering and
Information Technology
sorted()

• The sort() method changes nums = 100, 10, 1, 8, 13, 5


the list in place hence it is not print(nums)

available for immutable sorted_nums = sorted(nums)


sequences print(sorted_nums)

str = "Hello World"


print(str)
• Python has a built-in method
to sorted() to create a new sorted_str = sorted(str)
print(sorted_str)
sorted list from an iterable

College of Engineering and


Information Technology
sorted() def get_name(emp):
return emp[0]

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))

College of Engineering and


Information Technology

You might also like