0% found this document useful (0 votes)
23 views28 pages

2 ListsTuples

The document is a lecture on Python programming, specifically focusing on strings, lists, and tuples. It covers string manipulation, list operations, and the differences between mutable and immutable data types. Additionally, it provides examples of using loops and functions to work with these data structures in Python.

Uploaded by

gamer.guy123679
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views28 pages

2 ListsTuples

The document is a lecture on Python programming, specifically focusing on strings, lists, and tuples. It covers string manipulation, list operations, and the differences between mutable and immutable data types. Additionally, it provides examples of using loops and functions to work with these data structures in Python.

Uploaded by

gamer.guy123679
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

CSCI2040:

Lists and Tuples


Yim-Pan CHUI
Computer Science & Engineering Department
The Chinese University of Hong Kong

CSCI2040 Introduction to Python 1


Strings
• Text is most common form of data in our daily life
• In Python, they are stored as a sequence of characters internally
• The length of a string can be varied during program execution
• Use single quote 'or double quote " to delimit

CSCI2040 Introduction to Python 2


Strings
• Enclosed either by single quote 'or double quote "

• >>> 'doesn\'t' Use \ to tell not delimit


"doesn't" character, \ is called escape
>>> "doesn't" char
"doesn't"
>>> '"Yes," \nhe said.' \n move the cursor to next
'"Yes," \nhe said.' line, a.k.a newline character
>>> print ('"Yes," \nhe said.')
"Yes,"
he said. Another way to print " when
>>> "\"Yes,\" he said." delimit is also "
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
CSCI2040 Introduction to Python 3
Strings
• Concatenated or repeated with + and * respectively

>>> word = 'CUHK'+ 'super'


>>> word
'CUHKsuper'
>>> '['+word*3 + ']'
'[CUHKsuperCUHKsuperCUHKsuper]'

CSCI2040 Introduction to Python 4


Strings
• Access can be in subscripted notation
>>> word[2]
'H'

• substrings can be specified with the slice notation


>>> word[0:2]
'CU'
>>> word[:2]
'CU'
>>> word[1:]
'UHKsuper'

• For non-negative indices, the length of a slice is the difference of the indices,
if both are within bounds

CSCI2040 Introduction to Python 5


Strings
• Immutable – can't be modified once created
>>> word[0] = 2
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
word[0] = 2
TypeError: 'str'object does not support item assignment

• But we can create a new string in this case


>>> word[0:3]+ " course"
'CUH course'
CSCI2040 Introduction to Python 6
Splitting Strings
• useful to break a string into, say words
• takes one argument, the character that separates the parts of the string
1 message = "CSCI2040 is really boring !!!, really very boring."
2 words = message.split(' ') # split uses ' '(or space) as separator
3 print(words)
4
5 words = message.split('really') # split uses 'really'as separator
6 print(words)
7
8
['CSCI2040', 'is', 'really', 'boring', '!!!,', 'really', 'very', 'boring.']
['CSCI2040 is ', ' boring !!!, ', ' very boring.']
CSCI2040 Introduction to Python 7
String functions
Note the use of '.'to call the string function
• Operation Description
s.capitalize() capitalize the first character of s
s.count(sub) count number of occurrence of sub in s
s.find(sub) find first index of sub in s, or -1 if not found
s.index(sub) find first index of sub in s, or raise a ValueError if not found
s.rfind(sub) find last index of sub in s, or -1 if not found
s.rindex(sub) find last index of sub in s, or raise a ValueError if not found
s.lower() convert s to lowercase
s.split() return a list of words in s
s.join(lst) join a list of words into a single string with s as separator
s.strip() strips leading/trailing white space from s
s.upper() convert s to upper case
s.replace(old,new) replace all instances of old with new in string
CSCI2040 Introduction to Python 8
What is a list?
List
• A list is a collection of things!
Like a cabinet
containing many
Ordinary drawers.
Variable
Each drawer stores one
Like a box for storing one value.
value
We can refer to each
drawer as 1st drawer, 2nd
drawer, 3rd drawer, etc.

CSCI2040 Introduction to Python 9


Lists
• A compound data types that group a number of comma separated
values
>>> squares = [1, 4, 9, 16, 25]

• Access to individual entry is possible through index


>>> squares[1]
4

• Note that index of list start from 0

CSCI2040 Introduction to Python 10


Lists
• Data type of list entries can be of different
>>> squares[1] = 'Hello'
>>> squares
[1, 'Hello', 9, 16, 25]

• Can index backward, -1 means the last item


>>> squares[-1]
25
>>> squares[-4] = 4
>>> squares
[1, 4, 9, 16, 25]

CSCI2040 Introduction to Python 11


Lists
• Also support slicing operation
• >>> squares[-3:]
[9, 16, 25]

• >>> squares[:3]
[1, 4, 9]
• >>> squares[:]
[1, 4, 9, 16, 25]

CSCI2040 Introduction to Python 12


Lists
• Support concatenation
>>> squares = squares + [36, 49, 64, 81, 100]
>>> squares
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

• Can also add entry through built-in methods


>>> squares.append(121)
>>> squares[10]
121

CSCI2040 Introduction to Python 13


Lists
• Changes to slice is also possible
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']

• Removing slice
>>> letters[2:5]=[]
>>> letters
['a', 'b', 'f', 'g']

CSCI2040 Introduction to Python 14


Lists
• Sometimes we may want to know how many entries are there in a list
• Built-in function len() can help

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']


>>> len(letters)
7

CSCI2040 Introduction to Python 15


for statement
• Iterate over items in a sequence i.e. lists
• Best suit operating on list

1 a = ['HKU', 'CUHK', 'UST']


2 for x in a:
3 print (x, len(x))
4 HKU 3
5 CUHK 4
6 UST 3
7
8
9
CSCI2040 Introduction to Python 16
for statement
• range() function to help iterate over number sequence similar to while
• Note it start from 0

1 for i in range(5):
2 print (i)
3
4 Output
5 0
6 1
7 2
8 3
9 4
CSCI2040 Introduction to Python 17
for statement
• range() function combine with len() can iterate over elements in a list
• We retrieve the item through their index here

1 a = ['Mary', 'had', 'a', 'little', 'lamb']


2 for i in (range(len(a))):
3 print (i, a[i])
4 Output
5 0 Mary
6 1 had
7 2 a
8 3 little
9 4 lamb
CSCI2040 Introduction to Python 18
More about range()
• You can have more precise control over range()
• range(initial, final, step)

• range(5, 10)
5, 6, 7, 8, 9

• range(0, 10, 3)
0, 3, 6, 9

• range(-10, -100, -30)


-10, -40, -70

CSCI2040 Introduction to Python 19


Lists
• we can't use a number larger (or less than) the dimension of the list

cse_teachers = ['John C.S. Lui', 'Patrick P.C. Lee', 'James Cheng', 'Wei Meng']
print ("first element in the list is =", cse_teachers[6])
#print ("first element in the list is =", cse_teachers[-7])

Traceback (most recent call last):


File "/COURSE/2040/list1.py", line 5, in <module>
print ("first element in the list is =", cse_teachers[6])
IndexError: list index out of range

CSCI2040 Introduction to Python 20


Enumerating a list
cse_teachers = ['john c. s. lui', 'patrick p. c. lee', 'james cheng', 'wei Meng']
print ("------- use enumerate -----------")
for index, teacher in enumerate(cse_teachers):
position = str(index)
print("Position: " + position + " Teacher: " + teacher.title())
print ("------- use list.index(value) -----------")
for teacher in cse_teachers:
print("Position:", cse_teachers.index(teacher), "Teacher: " + teacher)

------- use enumerate -----------


Position: 0 Teacher: John C. S. Lui
Position: 1 Teacher: Patrick P. C. Lee
Position: 2 Teacher: James Cheng
Position: 3 Teacher: Wei Meng
------- use list.index(value) -----------
Position: 0 Teacher: john c. s. lui
Position: 1 Teacher: patrick p. c. lee
Position: 2 Teacher: james cheng
Position: 3 Teacher: wei Meng CSCI2040 Introduction to Python 21
Testing for item membership
cse_teachers = ['john c. s. lui', 'patrick p. c. lee', 'y.p.chui', 's.h.or']

print ("Is 'john c. s. lui'in the list?", 'john c. s. lui'in cse_teachers)


print ("Is 'John C. S. Lui'in the list?", 'John C. S. Lui'in cse_teachers)

Is 'john c. s. lui'in the list? True


Is 'John C. S. Lui'in the list? False

CSCI2040 Introduction to Python 22


List Operations
Operation Description
s.append(x) appends element x to s
s.extend(ls) appends list s with ls
s.count(x) count number of occurrence of x in s
s.index(x) return index of first occurrence of x
s.pop() return and remove last element from s
s.pop(i) return and remove element i from s
s.remove(x) search for x and remove it from s
s.reverse() reverse element of s in place
s.sort() sort elements of s into ascending order
s.insert(i, x) inserts x at location i

CSCI2040 Introduction to Python 23


Tuples
• Similar to list, but form using parenthesis
• Immutable, major difference compare with list
• Non-mutable operations in list can apply to tuple

>>> tup = (1,7,3,1,7,3)


>>> 3 in tup
True
>>> list(tup)
[1, 7, 3, 1, 7, 3]
>>> tuple(['a', 'b', 'c'])
('a', 'b', 'c')
CSCI2040 Introduction to Python 24
Tuples
• Comma operator implicitly creates a tuple
>>> 'a','b','c'
('a', 'b', 'c')

• Application in function returning more than 1 result

def minAndMax( info ):


return (min(info), max(info))
>>> x, y = minAndMax( 'abcd')
>>> x
'a'
>>> y
'd'
CSCI2040 Introduction to Python 25
What good list & strings brings?
• Consider the following problem:
Write a program to check whether an input string is a strong password,
which has to contain…

1. lower case letters,


2. upper case letters,
3. digits,
4. special characters, and
5. the length has to be no shorter than 12.

• We would do this by testing one by one


CSCI2040 Introduction to Python 26
What good list & strings brings?
• In C language, we would proceed to test the ASCII code of input string
character by character

• char pw[100];
int cnt=0;
Need to think of character, loop ,
character function
scanf("%s", pw); Many low level thinking
for (i=0; i<strlen(pw); i++)
if (islower(pw[i]) cnt++;
if (cnt<=0) printf("No lower case ");

CSCI2040 Introduction to Python 27


What good list & strings brings?
• In Python, the thinking is different

password=input("Enter your password: ")


has_lowercase = False
lowercase='abcdefghijklmnopqrstuvwxyz'
for c in password:
has_lowercase = has_lowercase or (c in lowercase)
if not has_lowercase:
print('No lowercase ')
CSCI2040 Introduction to Python 28

You might also like