0% found this document useful (0 votes)
4 views83 pages

B13!05!06_Python_Collection Data Types and String

Uploaded by

nthang0987
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
4 views83 pages

B13!05!06_Python_Collection Data Types and String

Uploaded by

nthang0987
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 83

Python Collection Data Types

and Strings
Lê Ngọc Hiếu
lnhieu@hcmute.edu.vn
Collection Data Types in Python
• Python has 4 built-in data structures that can be used to
hold a collection of objects.
• List
• Tuple
• Set
• Dictionary

2
1. Python List

2. Python Tuple

Lecture 3. Python Set

Contents 4. Python Dictionary

5. Python String

6. Exercises
3
Python List

4
What is a List?
• A list is an ordered collection of items.
• Notes on syntax:
• Begin with [ and end with ]
• Commas separate the individual values.
• Any type of object can be stored in a list.
• Each list can mix different types.
• Allows duplicate members.
• A list can contain other lists.
• Lists are mutable objects, i.e., we can
modify the list after it is created.
• For examples: change item values, add
new items, remove items, sort the list.

5
Access List Items
• Each item in the list is associated with a unique
index.
• The first item has index [0], the second item has
index [1], …
• Negative Indexing:
• Negative indexing means start from the end.
• -1 refers to the last item, -2 refers to the second
last item, …
• Range of Indexes
• By specifying where to start and where to end
the range, we can access to a part of a list.
• By leaving out the start value, the range will start
at the first item.
• By leaving out the end value, the range will go on
6
Change List Items
Change one item value:
• Use the index number to change
the value of a specific item.

Change multiple item values:


• Case 1: Replace n items with n
new values.
• Case 2: Replace n items with m
new values (m > n).
• Case 3: Replace n items with m
new values (m < n).
7
Change List Items

8
Add List Items
• append() method
• Add one item to the end of the list.
• insert() method
• Insert one item at a specified index.
• extend() method
• Append elements from another list to
the current list.
• Can be used to append any iterable
object.

9
Add List Items

10
Remove List Items
Remove Specified Item
• The remove() method removes the
specified item.
Remove Specified Index
• The pop() method removes the specified
index.
• If no index is specified, the pop() method
removes the last item.
Clear the List
• The clear() method empties the list.
• The list still remains, but it has no content.
del Keyword
• The del keyword can be used to remove the
specified index.
11
Remove List Items

12
Loop Lists
Loop Through a List
• Use a for loop to loop
through all list items.

Loop Through the


Index Numbers
• Use item indexes to loop
through the list items.
• Use the range() and
len() functions to create
a suitable iterable.
13
Sort Lists
• A list can be sort in
ascending (by
default) or
descending order
using sort() method.

• The sort() method


only work with lists of
numbers or lists of
strings.

14
Sort Lists
• By default, the sort() method is case sensitive, resulting in
all capital letters being sorted before lower case letters.
• To perform a case-insensitive sort, use str.lower as a key
function.

15
Customize Sort Function
• You can customize the sort function by using the keyword
argument key = function.
• Syntax: list_variable.sort(key = your_function)
• Example: sort the list based on how close the number is to
50.

16
Customize Sort Function - Example
• Given a list whose elements are lists of two integers.
• Sort the list based on the second element.

17
Customize Sort Function - Example
• Given a list whose elements are points in the Oxy
coordinate.
• Sort the list based on how close the point is to the origin.

18
Reverse lists
• The reverse() method reverses the order of the list items.

20
Copy Lists
• Use the built-in list method copy().

• Use the built-in method list().

• Cannot copy a list by typing list2 = list1. Because:


• list2 will only be a reference to list1,
• And changes made in list1 will automatically also be made in list2.
21
Join Lists
• There are several ways to join, or concatenate, two or more
lists in Python.
• Use +
+ operator
operator • Use append • Use extend
method method

22
Summary of List Methods
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the
current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list 23
List Comprehension
• List comprehension offers a shorter syntax when you want
to create a new list based on the values of an existing list.
• Example:
• Given a list of integers.
• Create a new list containing squares of all elements in the
given list.

24
List Comprehension
• List comprehension offers a shorter syntax when you want
to create a new list based on the values of an existing list.
• Example:
• Given a list of integers.
• Create a new list containing squares of all elements in the
given list.

Without list comprehensive With list comprehensive


25
List Comprehension – Basic Syntax
• Syntax: newlist = [output_expression for item in list]

26
List Comprehension – with if condition
• Syntax: newlist = [output_expression for item in list
if condition == True]

27
List Comprehension - Example
• Given list of top five highest mountains on Earth.
• Create a list of mountains where the height is greater than
8600 meters.
mountains = [
['Makalu', 8485],
['Lhotse', 8516],
['Kanchendzonga', 8586],
['K2', 8611],
['Everest', 8848]
]
highest_mountains =

28
List Comprehension - Example
• Create a list of all prime numbers between 100 and 200.
# (1) write a function to check if a number is prime number

# (2) use list comprehensive to create a list of prime numbers

29
Python Tuple

31
Definition of Tuple
• Tuples are used to store multiple items in a single variable.
• A tuple is a collection which is ordered and unchangeable.
• Tuples are written with round brackets.
• A tuple can contain different data types.
• We can use tuples in much the same way as we use lists.
Tuple Operator and Methods
Operato
r/ Description Example
Method
tuple1 = ("a", "b" , "c")
+ operat tuple2 = (1, 2, 3)
To join two or more tuples
or tuple3 = tuple1 + tuple2
print(tuple3)
fruits = ("apple","banana","cherry")
* To multiply the content of a
mytuple = fruits * 2
operator tuple print(mytuple)
thistuple = (1,3,5,8,7,5,4,6)
Returns the number of times a
count() x = thistuple.count(5)
specified value occurs in a tuple print(x)
Returns the index of the first thistuple = (1,3,7,8,7,5,4,6,8,5)
index() element with the specified x = thistuple.index(8)
value print(x)
thistuple = 33
Python Set
Set
• Sets are used to store multiple items
in a single variable.
• Set items are unordered,
unchangeable, and do not allow
duplicate values.
• Note: Set items are unchangeable,
but you can remove items and add
new items to a set.
• Sets are written with curly brackets.
• A set can contain different data types.
• The set() constructor can be used to
make a set.
• The len() method can be used to get
the length of a set.
Access Set Items
• Cannot access items in a set by referring to an index or a
key.
• Use the in keyword to loop through the set items or two
check if a value exists in a set.

36
Add Set Items
• Once a set is created, you
cannot change its items, but
you can add new items.
• To add one item to a set, use
the add() method.
• To add items from another
set into the current set, use
the update() method.
• Update() method can work
with any iterable object
(tuples, lists, dictionaries
etc.) 37
Remove Set Items
• Use remove() method • Use pop() method to
remove the last item.

• Use discard() method

38
Remove Set Items
• Use clear() method to empty the set

• Use del keyword to delete the set completely.

39
Set Operations - Union
• union() method • update() method

40
Set Operations - Intersection
• intersection() method • intersection_update()
method

41
Set Operations –Difference
• difference() method • difference_update()
method

42
Set Operations – Symmetric
Difference
• symmetric_difference() • symmetric_difference_updat
method e() method

43
Summary of Set Methods
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two
or more sets
difference_update() Removes the items in this set that are also included in
another, specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other
sets
intersection_update() Removes the items in this set that are not present in
other, specified set(s)
44
Summary of Set Methods
Method Description
isdisjoint() Check if two sets have an intersection
issubset() Check if another set contains this set
issuperset() Check if this set contains another set
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences
of two sets
symmetric_difference_updat Inserts the symmetric differences from this set
e() and another
union() Return a set containing the union of sets
update() Update the set with the union of this set and
others 45
Set comprehension
• Similar to list comprehension.
• Syntax: {expression for element in set if
condition}
• Example:

46
Python Dictionary
Python Dictionaries
• Dictionaries are used to store data
values in key:value pairs.
• A dictionary is a collection which is
ordered (as of Python version 3.7),
changeable.
• Dictionaries cannot have two items with
the same key.
• Dictionaries are written with curly
brackets and have keys and values.
• The len() function is used to get the
number of items in a dictionary.
• The values in dictionary items can be of
any data type.
Access Dictionary Items
• Dictionary items can be • To get the list of all the
accessed by: keys in a dictionary, use
• Its key name, inside square keys() method.
brackets.
• Or using get() method.

49
Change Dictionary Items
• Change values of a specific • Update the dictionary with
item by referring to its key the items from the given
name. argument using update()
method.

50
Add Dictionary Items
• Adding Items • Update Dictionary
• Use a new index key and • Use update() method.
assigning a value to it.

51
Remove Dictionary Items
• Remove an item with the
specified key name by:
• pop() method
• del keyword
• Remove the last item by
popitem() method.
• Clear a dictionary by clear()
method.
• Delete a dictionary completely
by del keyword.

52
Loop
Through a
Dictionary

53
Copy Dictionaries
• Cannot copy a dictionary by typing dict2 = dict1,
because:
• dict2 will only be a reference to dict1,
• Changes made in dict1 will automatically be made in dict2.
• To copy a dictionary:
• Use the built-in Dictionary method copy().
• Use the built-in function dict().

54
Nested Dictionaries
• A dictionary can contain dictionaries, this is called nested
dictionaries.

55
Summary: Dictionary Methods
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
Returns the value of the specified key. If the key does not
setdefault()
exist, insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
56
Dictionary Comprehension
• Similar to list comprehension.
• Syntax: {key:value for item in iterable if
condition}
• Example:
• Create a dictionary where the key is an integer between 1
and 10, and the value is the square root of the key.

57
Dictionary Comprehension
• Similar to list comprehension.
• Syntax: {key:value for item in iterable if
condition}
• Example:
• Create a dictionary where the key is an integer between 1
and 10, and the value is the square root of the key.

58
Dictionary Comprehension - Example
• Given a dictionary whose items are stock symbol and price.
• Create a new dictionary where the stock prices are
increased by 2%
• Create a dictionary containing stocks whose prices are
greater than 200.

59
Python Strings

62
Definition of Strings
• A string is a sequence of characters wrapped inside single,
double, or triple quotes.
• In Python, strings are immutable.
• An immutable object can’t be changed after it is created.
• The followings are valid string literals in Python.
• 'This is a string in Python'
• "This is a string in Python"
• '''This is a string in Python'''
• """This is a string in Python"""
• String can be printed or assigned to variables

63
Combining Single and Double Quotes in a String
• If a string contains a single quote, it should be placed in
double-quotes.
• If a string contains double quotes, it should be placed in
single quotes.

64
Multi-Line Strings
• Multiline strings must be placed in triple quotes.

65
Escape Characters
• To insert characters that are illegal in a string, use an
escape character.
• An escape character is a backslash \ followed by the
character you want to insert.

66
Strings are Arrays
• Strings in Python are arrays of bytes representing Unicode
characters.
• Python does not have a character data type.
• A single character is simply a string with a length of 1.
• Indexes and square brackets can be used to access
elements of the string.
• Example:
• Given a string s = ‘Hello’
• We can access all elements of s by writing s[0], s[1], s[2], s[4], s[5].

67
Slicing Strings
• Use the slide syntax to return a range of characters.
• Specify the start index and the end index, separated by a
colon, to return a part of the string.
• Example: Given the string s = "Hello, World!"

68
Slicing Strings
• Slice From the Start
• By leaving out the start
index, the range will start
at the first character.
• Slice To the End
• By leaving out the end
index, the range will go to
the end.
• Negative Indexing
• Use negative indexes to
start the slice from the
end of the string. 69
String Operations
Concatenation + Replication *
• To concatenate, or combine, • You can replicate strings by
two strings you can use the + multiplying them by an integer.
operator. • Example:
• Examples:

• What happens if we multiply a


string by a negative integer or
0?
70
String Operations
• in: Check if a character exists in a given string.
• not in: Check if a character does not exist in a given string.

71
String Functions
Function
Description Example
name
s = "Hello!"
len() Return the length of a string.
N = len(s)
Convert an integer or float a = 8.5
str()
to a string. s = str(a)
Convert a string that is in
s = '2'
int() the form of an integer to an
a = int(s)
integer.
Convert a string that is in s = '2'
float()
the form of a float to a float. b = float(s)
72
Python String Formatting
• There are various ways to format strings in Python.
• Common ways:
1. Use format() method.
2. Use f-strings: an improvement from Python 3.6

73
format() Method
• The format() method allows you to format selected parts
of a string.

74
format() Method - Syntax
• The format() method formats the specified value(s) and
insert them inside the string's placeholder.
• The placeholder is defined using curly brackets {}.
• The format() method returns the formatted string.
• Syntax: string.format(value1, value2...)
• value1, value2...: One or more values that should be
formatted and inserted in the string.
• The values are either a list of values separated by commas, a
key=value list, or a combination of both.
• The values can be of any data type.

75
format() Method - Placeholders
• The placeholders can be identified using named indexes,
numbered indexes, or even empty placeholders {}.

76
format() Method - Formatting Types
• Inside the placeholders you can add a formatting type to
format the result.
• Examples:

77
f-strings
• Formatted string literals (also called f-strings for short) is
used to include the value of Python expressions inside a
string.
• To use f-strings, prefix the string with f or F and write
expressions as {expression}.
• Examples:

79
Python String Methods
Method
Description Examples of usage
name
Converts the first
txt = "hello and welcome "
capitalize() character to upper
x = txt.capitalize()
case.
txt = "Hello, And Welcome To My
Converts string into
casefold() World!"
lower case.
x = txt.casefold()
Converts a string txt = "Hello my friends"
upper()
into upper case. x = txt.upper()

txt = "banana"
x = txt.center(20)
center(lengt Returns a centered
h, character) string.
txt = "banana" 80
Python String Methods
Method
Description Examples of usage
name
txt = "I love apples, apple are my
Returns the number favorite fruit"
count(value, of times a specified x = txt.count("apple")
start, end) value occurs in a txt = "I love apples, apple are my
string. favorite fruit"
x = txt.count("apple", 10, 24)
• Returns the first txt = "Hello, welcome to my world."
occurrence of the x = txt.find("welcome")
find(value,
specified value.
start, end) txt = "Hello, welcome to my world."
• Return -1 if not
found. x = txt.find("e", 5, 10)
• Return the last txt = "Hello, welcome to my world."
occurrence of the x = txt.rfind("e") 81
rfind(value,
Python String Methods
Method
Description Examples of usage
name
txt = "Hello, welcome to my world."
Returns true if the x = txt.endswith("my world.")
endswith(valu
string ends with the
e, start, end) txt = "Hello, welcome to my world."
specified value.
x = txt.endswith("my world.", 5, 11)
txt = "Hello, welcome to my world."
Returns true if the x = txt.startswith("Hello")
startswith(valu
string starts with the
e, start, end) txt = "Hello, welcome to my world."
specified value.
x = txt.startswith("wel", 7, 20)
txt = "good day, good trip, good
Returns a string holiday."
replace(oldval x = txt.replace("good", "nice")
where a specified
ue, newvalue,
value is replaced with txt = "good day, good trip, good 82
Python String Methods
Method
Description Examples of usage
name
txt = "Company12"
Returns True if all characters x = txt.isalnum()
isalnum() in the string are
alphanumeric. txt = "Company 12"
x = txt.isalnum()
txt = "CompanyX"
Returns True if all characters x = txt.isalpha()
isalpha() in the string are in the
alphabet. txt = "Company10"
x = txt.isalpha()
txt = "50800"
Returns True if all characters x = txt.isdigit()
isdigit()
in the string are digits. txt = "508.00"
x = txt.isdigit()
83
Python String Methods
Method
Description Examples of usage
name
Returns True if all
a = "hello 123"
islower() characters in the string are
print(a.islower())
lower case.
Returns True if all
a = "MY NAME IS PETER"
isupper() characters in the string are
print(a.isupper())
upper case.
txt = "I could eat bananas all
Returns a tuple where the day"
partition(valu
string is parted into three x = txt.partition("bananas")
e)
parts. # x = ('I could eat ', 'bananas', '
all day')
txt = "apple%banana%cherry"
x = txt.split("%") 84
Exercises

85
Write a function to:
1. Sum all the items in a list of integers.
2. Multiply all the items in a list of integers.
3. Get the largest number from a list of integers.
4. Get the smallest number from a list of integers.
5. Get the average of all the items in a list of integers.
6. Find all the values in a list are greater than a specified number.
7. Sorted in increasing order by the last element in each tuple from a given list of non-empty tuples.
Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
8. Remove duplicates from a list.
9. Check a list is empty or not.
10. Write a function that takes two lists and returns True if they have at least one common member.
11. Get all different items between the two lists.
12. Find the items starts with specific character from a given list.
13. Generate a list that contains the first N prime numbers.
14. Generate a list that contains the first N Fibonacci numbers.
15. Generate a list that contains the first N perfect numbers.

86
16.Generate a dictionary where the keys are numbers between 1 and N (both
included) and the values are square of keys.
Sample input : N = 5
Expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
17.Combine two dictionary adding values for common keys.
Sample input: d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}
Expected output: {'a': 400, 'b': 400, ‘c’: 300, ‘d’: 400}
18.Count the frequency in a given dictionary.
Sample input:
{'A': 10, 'B': 10, 'C': 40, 'D': 20, 'E': 70, 'F': 80, 'G': 40, 'H': 20}
Expected output: {10: 2, 40: 2, 20: 2, 70: 1, 80: 1}
19.Given a list of points. Each point has x-coordinate and y- coordinate. The
coordinate of a point is stored in a tuple.
a) Count the number of points in each quadrants.
b) Find the centroid of all points.
Sample input: [(1, 1), (-2, 1), (-3, -5), (2, -1), (2, 5)] 87
20.Count the number of characters (character frequency) in
a string.
• Sample input : ' google.com'
• Expected Result : {'g': 2, 'o': 3, 'l': 1, 'e': 1, '.': 1, 'c': 1, 'm':
1}
21.Find the length of the longest word in a sentence.
22.Find the longest common sub-string from two given
strings.
23.Given a list of strings. Sort the list by the length of each
string.
24.Given a dictionary as below. Sort the list by a given key.

88

You might also like