4 Data Types - Final
4 Data Types - Final
Data Types
1
4: Data Types in Python
2
Integers
• Integers are numbers with no decimal parts,
such as -5, -4, -3, 0, 5, 7 etc.
• To declare an integer in Python, simply write
variableName = initial value
• Example:
userAge = 20,
mobileNumber = 12398724
3
Float
• Float refers to numbers that have decimal
parts, such as 1.234, -0.023, 12.01.
• To declare a float in Python, we write
variableName = initial value
• Example:
userHeight = 1.82, userWeight = 67.2
4
String
• String refers to text.
• To declare a string, you can either use variableName = ‘initial value’ (single
quotes) or variableName = “initial value” (double quotes)
• Example:
userName = ‘Peter’, userSpouseName = “Janet”, userAge = ‘30’
8
• In the example above, the string
• ‘The price of this %s laptop is %d USD and the exchange
rate is %4.2f USD to 1 EUR’ is the string that we want to
format.
• We use the %s, %d and %4.2f formatters as laceholders in
the string.
• These placeholders will be replaced with the variable
brand, the value 1299 and the variable exchangeRate
respectively, as indicated in the
• round brackets.
• If we run the code, we’ll get the output below.
9
• The price of this Apple laptop is 1299 USD and the
exchange rate is 1.24 USD to 1 EUR
• The %s formatter is used to represent a string
(“Apple” in this case)
• The %d formatter represents an integer (1299). If
we want to add spaces before an integer, we can
add a number between % and d to indicate the
desired length of the string. For instance “%5d”
%(123) will give us “ 123” (with 2 spaces in front
and a total length of 5).
10
• The %f formatter is used to format floats
(numbers with decimals).
• Here we format it as %4.2f where 4 refers to
the total length and 2 refers to 2 decimal
places.
• If we want to add spaces before the number,
we can format is as %7.2f, which will give us
“ 1.24” (with 2 decimal places, 3 spaces in
front and a total length of 7).
11
• Formatting Strings using the format() method
• In addition to using the % operator to format
strings, Python also provides us with the
format() method to format strings.
• The syntax is
• “string to be formatted”.format(values or
variables to be inserted into string, separated
by commas)
12
• When we use the format method, we do not use %s, %f
or %d as placeholders.
• Instead we use curly brackets, like this:
• message = ‘The price of this {0:s} laptop is {1:d} USD and
the exchange rate is {2:4.2f} USD to 1
EUR’.format(‘Apple’, 1299, 1.235235245)
• Inside the curly bracket, we first write the position of the
parameter to use, followed by a colon.
• After the colon, we write the formatter.
• There should not be any spaces within the curly brackets.
13
• When we write format(‘Apple’, 1299, 1.235235245),
we are passing in three parameters to the format()
method.
• Parameters are data that the method needs in order
to perform its task.
• The parameters are ‘Apple’, 1299 and 1.235235245.
• The parameter ‘Apple’ has a position of 0, 1299 has
a position of 1 and 1.235235245 has a position of 2.
• Positions always start from ZERO.
14
• When we write {0:s}, we are asking the interpreter to
replace {0:s} with the parameter in position 0 and
that it is a string (because the formatter is ‘s’).
• When we write {1:d}, we are referring to the
parameter in position 1, which is an integer
(formatter is d).
• When we write {2:4.2f}, we are referring to the
parameter in position 2, which is a float and we want
it to be formatted with 2 decimal places and a total
length of 4 (formatter is 4.2f).
15
• If we print the message, we’ll get
• The price of this Apple laptop is 1299 USD and
the
• exchange rate is 1.24 USD to 1 EUR
• Note: If you do not want to format the string,
you can simply write
• message = ‘The price of this {} laptop is {} USD
and the exchange rate is {} USD to 1
EUR’.format(‘Apple’, 1299, 1.235235245)
16
• Here we do not have to specify the position of
the parameters.
• The interpreter will replace the curly brackets
based on the order of the parameters
provided. We’ll get
• The price of this Apple laptop is 1299 USD and
the exchange rate is 1.235235245 USD to 1
EUR
17
• In fact, string formatting can be more fanciful
than what we’ve covered here, but what
we’ve covered is sufficient for most purposes.
• To get a better understanding of the format()
method, try the following program.
18
• message1 = ‘{0} is easier than {1}’.format(‘Python’, ‘Java’)
• message2 = ‘{1} is easier than {0}’.format(‘Python’, ‘Java’)
• message3 = ‘{:10.2f} and {:d}’.format(1.234234234, 12)
• message4 = ‘{}’.format(1.234234234)
• print (message1)
• #You’ll get ‘Python is easier than Java’
• print (message2)
• #You’ll get ‘Java is easier than Python’
• print (message3)
• #You’ll get ‘ 1.23 and 12’
• #You do not need to indicate the positions of the parameters.
• print (message4)
• #You’ll get 1.234234234. No formatting is done.
Use the Python Shell to experiment with the format() method
19
Type Casting In Python
• Sometimes it is necessary to convert from one data type to another,
such as from an integer to a string. This is known as type casting.
• There are three built-in functions in Python that allow us to do type
casting:
• These are the int(), float(), and str() functions.
• The int() function in Python takes in a float or an appropriate string
and converts it to an integer.
• To change a float to an integer, we can type int(5.712987). We’ll get
5 as the result (anything after the decimal point is removed).
• To change a string to an integer, we can type int(“4”) and we’ll get 4.
• However, we cannot type int(“Hello”) or int(“4.22321”). We’ll get an
error in both cases.
20
• The float() function takes in an integer or an
appropriate string and changes it to a float.
For instance, if we type float(2) or float(“2”),
we’ll get 2.0. If we type float(“2.09109”), we’ll
get 2.09109 which is a float and not a string
since the quotation marks are removed.
• The str() function on the other hand converts
an integer or a float to a string. For instance, if
we type str(2.1), we’ll get “2.1”.
21
List
• List refers to a collection of data which are normally
related. Instead of storing these data as separate variables,
we can store them as a list. For instance, suppose our
program needs to store the age of 5 users. Instead of
storing them as user1Age, user2Age, user3Age, user4Age
and user5Age, it makes more sense to store them as a list.
• To declare a list, you write listName = [initial values]. Note
• that we use square brackets [ ] when declaring a list.
Multiple values are separated by a comma.
• Example:
• userAge = [21, 22, 23, 24, 25]
22
• We can also declare a list without assigning any
initial values to it. We simply write listName = [].
What we have now is an empty list with no items in
it. We have to use the append() method to add
items to the list.
• Individual values in the list are accessible by their
indexes, and indexes always start from ZERO, not 1.
• Hence the first value has an index of 0, the next has
an index of 1 and so forth. For instance, userAge[0]
= 21, userAge[1] = 22
23
• Alternatively, you can access the values of a list from
the back. The last item in the list has an index of -1,
the second last has an index of -2 and so forth. Hence,
userAge[-1] = 25, userAge[-2] = 24.
• You can assign a list, or part of it, to a variable. If you
write userAge2 = userAge, the variable userAge2
becomes [21, 22, 23, 24, 25].
• If you write userAge3 = userAge[2:4], you are assigning
items with index 2 to index 4-1 from the list userAge to
the list userAge3. In other words, userAge3 = [23, 24].
24
• The notation 2:4 is known as a slice. Whenever we use
the slice notation in Python, the item at the start index is
always included, but the item at the end is always
excluded. Hence the notation 2:4 refers to items from
index 2 to index 4-1 (i.e. index 3), which is why userAge3
= [23, 24] and not [23, 24, 25].
• The slice notation includes a third number known as the
stepper. If we write userAge4 = userAge[1:5:2], we will
get a sub list consisting of every second number from
index 1 to index 5-1 because the stepper is 2. Hence,
userAge4 = [22, 24].
25
• In addition, slice notations have useful defaults. The default
for the first number is zero, and the default for the second
number is size of the list being sliced.
• For instance, userAge[ :4] gives you values from index 0 to
index 4-1 while userAge[1: ] gives you values from index 1 to
index 5-1 (since the size of userAge is 5, i.e. userAge has 5
items).
• To modify items in a list, we write listName[index of item to be
modified] = new value.
• For instance, if you want to modify the second item, you write
userAge[1] = 5. Your list becomes userAge = [21, 5, 23, 24, 25]
26
• To add items, you use the append() function. For
instance, if you write userAge.append(99), you
add the value 99 to the end of the list. Your list is
now userAge = [21, 5, 23, 24, 25, 99]
• To remove items, you write del listName[index of
item to be deleted]. For instance, if you write del
userAge[2], your list now becomes userAge =
[21, 5, 24, 25, 99] (the third item is deleted)
27
• To fully appreciate the workings of a list, try running the following
program.
#declaring the list, list elements can be of different data types
myList = [1, 2, 3, 4, 5, “Hello”]
31
Dictionary
• Dictionary is a collection of related data PAIRS. For instance,
if we want to store the username and age of 5 users, we can
store them in a dictionary.
• To declare a dictionary, you write dictionaryName =
{dictionary key : data}, with the requirement that dictionary
keys must be unique (within one dictionary).
• That is, you cannot declare a dictionary like this
myDictionary = {“Peter”:38, “John”:51, “Peter”:13}.
• This is because “Peter” is used as the dictionary key twice.
• Note that we use curly brackets { } when declaring a
dictionary. Multiple pairs are separated by a comma.
32
• Example:
• userNameAndAge = {“Peter”:38, “John”:51, “Alex”:13,
“Alvin”:“Not Available”}
• You can also declare a dictionary using the dict( ) method.
To declare the userNameAndAge dictionary above, you
write
• userNameAndAge = dict(Peter = 38, John = 51, Alex = 13,
Alvin = “Not Available”)
• When you use this method to declare a dictionary, you use
round brackets ( ) instead of curly brackets { } and you do
not put quotation marks for the dictionary keys.
33
• To access individual items in the dictionary, we use the dictionary
key, which is the first value in the {dictionary key : data} pair.
• For instance, to get John’s age, you write
userNameAndAge[“John”].
• You’ll get the value 51.
• To modify items in a dictionary, we write
dictionaryName[dictionary key of item to be modified] = new
data.
• For instance, to modify the “John”:51 pair, we write
userNameAndAge[“John”] = 21.
• Our dictionary now becomes userNameAndAge = {“Peter”:38,
“John”:21, “Alex”:13, “Alvin”:“Not Available”}.
34
• We can also declare a dictionary without assigning any
initial values to it.
• We simply write dictionaryName = { }. What we have now
is an empty dictionary with no items in it.
• To add items to a dictionary, we write
dictionaryName[dictionary key] = data.
• For instance, to add “Joe”:40 to our dictionary, we write
userNameAndAge[“Joe”] = 40.
• Our dictionary now becomes userNameAndAge =
{“Peter”:38, “John”:21, “Alex”:13, “Alvin”:“Not Available”,
“Joe”:40}
35
• To remove items from a dictionary, we write
del dictionaryName[dictionary key].
• For instance, to remove the “Alex”:13 pair, we
write del userNameAndAge[“Alex”].
• Our dictionary now becomes
userNameAndAge = {“Peter”:38, “John”:21,
“Alvin”:“Not Available”, “Joe”:40}
36
Run the following program to see all these in action
• #declaring the dictionary, dictionary keys and data
can be of different data types
• myDict = {“One”:1.35, 2.5:”Two Point Five”, 3:”+”,
7.9:2}
• #print the entire dictionary
• print(myDict)
• #You’ll get {2.5: 'Two Point Five', 3: '+', 'One': 1.35,
7.9: 2}
• #Note that items in a dictionary are not stored in
the same order as the way you declare them.
37
• #print the item with key = “One”.
• print(myDict[“One”])
• #You’ll get 1.35
• #print the item with key = 7.9.
• print(myDict[7.9])
• #You’ll get 2
• #modify the item with key = 2.5 and print the updated
dictionary
• myDict[2.5] = “Two and a Half”
• print(myDict)
• #You’ll get {2.5: 'Two and a Half', 3: '+', 'One': 1.35, 7.9:
2}
38
• #add a new item and print the updated dictionary
• myDict[“New item”] = “I’m new”
• print(myDict)
• #You’ll get {'New item': 'I’m new', 2.5: 'Two and a Half', 3: '+',
'One': 1.35, 7.9: 2}
• #remove the item with key = “One” and print the updated
dictionary
• del myDict[“One”]
• print(myDict)
• #You’ll get {'New item': 'I’m new', 2.5: 'Two and a Half', 3: '+',
7.9: 2}
39
Appendix A -Strings
• Note: The notation [start, [end]] means start
and end are optional parameters. If only one
number is provided as the parameter, it is taken
to be start.
• # marks the start of a comment
• ‘’’ marks the start and end of a multiline
comment. The actual code is in monotype font.
• => marks the start of the output
40
count (sub, [start, [end]])
• Return the number of times the substring sub appears in the string.
• This function is case-sensitive.
• [Example]
# In the examples below, ‘s’ occurs at index 3, 6 and 10
# count the entire string
‘This is a string’.count(‘s’)
=> 3
# count from index 4 to end of string ‘This is a string’.count(‘s’, 4) => 2
# count from index 4 to 10-1
‘This is a string’.count(‘s’, 4, 10 ) => 1
# count ‘T’. There’s only 1 ‘T’ as the function is case sensitive.
‘This is a string’.count(‘T’)
=> 1
41
endswith (suffix, [start, [end]])
• Return True if the string ends with the specified suffix, otherwise return False.
• suffix can also be a tuple of suffixes to look for.
• This function is case-sensitive.
• [Example]
# ’man’ occurs at index 4 to 6
# check the entire string
‘Postman’.endswith(‘man’)
=> True
# check from index 3 to end of string ‘Postman’.endswith(‘man’, 3)
=> True
# check from index 2 to 6-1
‘Postman’.endswith(‘man’, 2, 6) => False
# check from index 2 to 7-1
‘Postman’.endswith(‘man’, 2, 7) => True
# Using a tuple of suffixes (check from index 2 to 6-1)
‘Postman’.endswith((‘man’, ‘ma’), 2, 6) => True
42
find/index (sub, [start, [end]])
• Return the index in the string where the first occurrence of the substring sub is found.
• find() returns -1 if sub is not found.
• index() returns ValueError is sub is not found.
• This function is case-sensitive.
• [Example]
# check the entire string
‘This is a string’.find(‘s’)
=> 3
# check from index 4 to end of string ‘This is a string’.find(‘s’, 4) => 6
# check from index 7 to 11-1
‘This is a string’.find(‘s’, 7,11 ) => 10
# Sub is not found
'This is a string'.find(‘p’)
=> -1
'This is a string'.index(‘p’)
=> ValueError
43
isalnum()
• Return true if all characters in the string are alphanumeric and there
is at least one character, false otherwise.
• Alphanumeric does not include whitespaces.
• [Example]
• ‘abcd1234’.isalnum()
• => True
• ‘a b c d 1 2 3 4’.isalnum()
• => False
• ‘abcd’.isalnum()
• => True
• ‘1234’.isalnum()
• => True
44
isalpha()
• Return true if all characters in the string are alphabetic and
there is at least one character, false otherwise.
• [Example]
• ‘abcd’.isalpha()
• => True
• ‘abcd1234’.isalpha()
• => False
• ‘1234’.isalpha()
• => False
• ‘a b c’.isalpha()
• => False
45
isdigit()
• Return true if all characters in the string are digits and there is
at least one character, false otherwise.
• [Example]
• ‘1234’.isdigit()
• => True
• ‘abcd1234’.isdigit()
• => False
• ‘abcd’.isdigit()
• => False
• ‘1 2 3 4’.isdigit()
• => False
46
islower()
• Return true if all cased characters in the string are
lowercase and there is at least one cased character,
false otherwise.
• [Example]
• ‘abcd’.islower()
• => True
• ‘Abcd’.islower()
• => False
• ‘ABCD’.islower()
• => False
47
isspace()
• Return true if there are only whitespace
characters in the string and there is at least
one character, false otherwise.
• [Example]
• ‘ ’.isspace()
• => True
• ‘a b’.isspace()
• => False
48
istitle()
• Return true if the string is a titlecased string
and there is at least one character
• [Example]
• ‘This Is A String’.istitle()
• => True
• ‘This is a string’.istitle()
• => False
49
isupper()
• Return true if all cased characters in the string are
uppercase and there is at least one cased character,
false otherwise.
• [Example]
• ‘ABCD’.isupper()
• => True
• ‘Abcd’.isupper()
• => False
• ‘abcd’.isupper()
• => False
50
join()
• Return a string in which the parameter provided is joined by a separator.
• [Example]
• sep = ‘-’
• myTuple = (‘a’, ‘b’, ‘c’)
• myList = [‘d’, ‘e’, ‘f’]
• myString = “Hello World”
• sep.join(myTuple)
• => ‘a-b-c’
• sep.join(myList)
• => ‘d-e-f’
• sep.join(myString)
• => ‘H-e-l-l-o- -W-o-r-l-d’’
51
lower()
• Return a copy of the string converted to
lowercase.
• [Example]
• ‘Hello Python’.lower()
• => ‘hello python’
52
replace(old, new[, count])
• Return a copy of the string with all occurrences of substring old
replaced by new.
• count is optional. If given, only the first count occurrences are
replaced.
• This function is case-sensitive.
• [Example]
• # Replace all occurences
• ‘This is a string’.replace(‘s’, ‘p’)
• => 'Thip ip a ptring'
• # Replace first 2 occurences
• ‘This is a string’.replace(‘s’, ‘p’, 2)
• => 'Thip ip a string'
53
split([sep [,maxsplit]])
• Return a list of the words in the string, using sep as the delimiter string.
• sep and maxsplit are optional.
• If sep is not given, whitespace is used as the delimiter.
• If maxsplit is given, at most maxsplit splits are done.
• This function is case-sensitive.
• [Example]
• ‘’’ Split using comma as the delimiter Notice that there’s a space before the
• words ‘is’, ‘a’ and ‘string’ in the output.
• ‘’’
• ‘This, is, a, string’.split(‘,’) => ['This', ' is', '
• a', ' string']
• # Split using whitespace as delimiter ‘This is a string’.split()
• => ['This', 'is', 'a', 'string']
• # Only do 2 splits
• ‘This, is, a, string’.split(‘,’ 2) => ['This', ' is', ' a, string']
54
splitlines ([keepends])
• Return a list of the lines in the string, breaking at line boundaries.
• Line breaks are not included in the resulting list unless keepends is given and true.
• [Example]
• # Split lines separated by \n
• ‘This is the first line.\nThis is the second line’.splitlines()
• => ['This is the first line.',
• 'This is the second line.']
• # Split multi line string (e.g. string that uses the ‘’’ mark)
• ‘’’This is the first line. This is the second line.’’’.splitlines()
• => ['This is the first line.', 'This is the second line.']
• # Split and keep line breaks
• 'This is the first line.\nThis is the second line.'.splitlines(True)
• => ['This is the first line.\n', 'This is the second line.']
• ‘’’This is the first line. This is the second line.’’’.splitlines(True)
• => ['This is the first line.\n', 'This is the second line.']
55
startswith (prefix[, start[, end]])
• Return True if string starts with the prefix, otherwise return False.
• prefix can also be a tuple of prefixes to look for.
• This function is case-sensitive.
• [Example]
• # check the entire string
• ‘Postman’.startswith(‘Post’)
• => True
• # check from index 3 to end of string
• ‘Postman’.startswith(‘Post’, 3)
• => False
• # check from index 2 to 6-1
• ‘Postman’.startswith(‘Post’, 2, 6)
• => False
• # check from index 2 to 6-1
• ‘Postman’.startswith(‘stm’, 2, 6)
• => True
• # Using a tuple of prefixes (check from index 3 to end of string)
• ‘Postman’.startswith((‘Post’, ‘tma’), 3)
• => True
56
strip ([chars])
• Return a copy of the string with the leading and trailing characters char
removed.
• If char is not provided, whitespaces will be removed.
• This function is case-sensitive.
• [Example]
• # Strip whitespaces
• ‘ This is a string ’.strip()
• => 'This is a string'
• # Strip ‘s’. Nothing is removed since ‘s’ is not at the start or end of the string
• 'This is a string'.strip('s')
• => 'This is a string'
• # Strip ‘g’.
• ‘This is a string’.strip(‘g’)
• => ‘This is a strin’
57
upper()
• Return a copy of the string converted to
uppercase.
• [Example]
• ‘Hello Python’.upper()
• => ‘HELLO PYTHON’
58
Appendix B-Working With Lists
append( )
• Add item to the end of a list
• [Example]
• myList = [‘a’, ‘b’, ‘c’, ‘d’]
• myList.append(‘e’) print (myList)
• => [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
59
del
• Remove items from a list
• [Example]
• myList = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’, ‘k’, ‘l’]
• #delete the third item (index = 2)
• del myList[2]
• print (myList)
• => [‘a’, ‘b’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’, ‘k’, ‘l’]
• #delete items from index 1 to 5-1
• del myList[1:5]
• print (myList)
• => [‘a’, ‘g’, ‘h’, ‘i’, ‘j’, ‘k’, ‘l’]
• #delete items from index 0 to 3-1
• del myList [ :3]
• print (myList)
• => [‘i’, ‘j’, ‘k’, ‘l’]
• #delete items from index 2 to end del myList [2:]
• print (myList)
• => [‘i’, ‘j’] 60
extend( )
• Combine two lists
• [Example]
• myList = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
• myList2 = [1, 2, 3, 4]
• myList.extend(myList2)
• print (myList)
• => [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, 1, 2, 3, 4]
61
In
• Check if an item is in a list
• [Example]
• myList = [‘a’, ‘b’, ‘c’, ‘d’]
• ‘c’ in myList
• => True
• ‘e’ in myList
• => False
62
insert( )
• Add item to a list at a particular position
• [Example]
• myList = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
• myList.insert(1, ‘Hi’) print (myList)
• => [‘a’, ‘Hi’, ‘b’, ‘c’, ‘d’, ‘e’]
63
len( )
• Find the number of items in a list
• [Example]
• myList = [‘a’, ‘b’, ‘c’, ‘d’]
• print (len(myList))
• => 4
64
pop( )
• Return the value of an item and remove it from the list
• Requires index of item as the parameter
• [Example]
• myList = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
• #remove the third item member
• myList.pop(2)
• print (member)
• => c
• print (myList)
• => [‘a’, ‘b’, ‘d’, ‘e’]
• #remove the last item member
• myList.pop( )
• print (member)
• => e
• print (myList)
• => [‘a’, ‘b’, ‘d’]
65
remove( )
• Remove an item from a list.
• Requires the value of the item as the parameter.
• [Example]
• myList = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
• #remove the item ‘c’
• myList.remove(‘c’)
• print (myList)
• => [‘a’, ‘b’, ‘d’, ‘e’]
66
reverse()
• Reverse the items in a list
• [Example]
• myList = [1, 2, 3, 4]
• myList.reverse()
• print (myList)
• => [4, 3, 2, 1]
67
sort()
• Sort a list alphabetically or numerically
• [Example]
• myList = [3, 0, -1, 4, 6]
• myList.sort()
• print(myList)
• => [-1, 0, 3, 4, 6]
68
sorted()
• Return a new sorted list without sorting the original list.
• Requires a list as the parameter
• [Example]
• myList = [3, 0, -1, 4, 6]
• myList2 = sorted(myList)
• #Original list is not sorted print (myList)
• => [3, 0, -1, 4, 6]
• #New list is sorted print (myList2)
• => [-1, 0, 3, 4, 6]
69
Addition Operator: +
• Concatenate List
• [Example]
• myList = [‘a’, ‘b’, ‘c’, ‘d’]
• print (myList + [‘e’, ‘f’])
• => [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
• print (myList)
• => [‘a’, ‘b’, ‘c’, ‘d’]
70
Multiplication Operator: *
• Duplicate a list and concatenate it to the end
of the list
• [Example]
• myList = [‘a’, ‘b’, ‘c’, ‘d’]
• print (myList*3)
• => ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']
• print (myList)
• => [‘a’, ‘b’, ‘c’, ‘d’]
71
• Note:
• The + and * symbols do not modify the list.
The list stays as [‘a’, ‘b’, ‘c’, ‘d’] in both cases.
72
Appendix C-Working With Tuples
• del
• Delete the entire tuple
• [Example]
• myTuple = (‘a’, ‘b’, ‘c’, ‘d’)
• del myTuple
• print (myTuple)
• => NameError: name 'myTuple' is not defined
73
in
• Check if an item is in a tuple
• [Example]
• myTuple = (‘a’, ‘b’, ‘c’, ‘d’)
• ‘c’ in myTuple
• => True
• ‘e’ in myTuple
• => False
74
len( )
• Find the number of items in a tuple
• [Example]
• myTuple = (‘a’, ‘b’, ‘c’, ‘d’)
• print (len(myTuple))
• => 4
75
Addition Operator: +
• Concatenate Tuples
• [Example]
• myTuple = (‘a’, ‘b’, ‘c’, ‘d’)
• print (myTuple + (‘e’, ‘f’))
• => (‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’)
• print (myTuple)
• => (‘a’, ‘b’, ‘c’, ‘d’)
76
Multiplication Operator: *
• Duplicate a tuple and concatenate it to the end of the
tuple
• [Example]
• myTuple = (‘a’, ‘b’, ‘c’, ‘d’)
• print(myTuple*3)
• => ('a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd')
• print (myTuple)
• => (‘a’, ‘b’, ‘c’, ‘d’)
• Note: The + and * symbols do not modify the tuple.
The tuple stays as [‘a’, ‘b’, ‘c’, ‘d’] in both cases.
77
Appendix D-Working With Dictionaries
clear( )
• Removes all elements of the dictionary, returning an
empty dictionary
• [Example]
• dic1 = {1: ‘one’, 2: ‘two’}
• print (dic1)
• => {1: 'one', 2: 'two'}
• dic1.clear()
• print (dic1)
• => { }
78
del
• Delete the entire dictionary
• [Example]
• dic1 = {1: ‘one’, 2: ‘two’}
• del dic1
• print (dic1)
• => NameError: name 'dic1' is not defined
79
get( )
• Returns a value for the given key.
• If the key is not found, it’ll return the keyword None.
• Alternatively, you can state the value to return if the key is not
found.
• [Example]
• dic1 = {1: ‘one’, 2: ‘two’}
• dic1.get(1)
• => ‘one’
• dic1.get(5)
• => None
• dic1.get(5, “Not Found”) => ‘Not Found’
80
In
• Check if an item is in a dictionary
• [Example]
• dic1 = {1: ‘one’, 2: ‘two’}
• # based on the key
• 1 in dic1
• => True
• 3 in dic1
• => False
• # based on the value
• ‘one’ in dic1.values()
• => True
• ‘three’ in dic1.values()
• => False 81
items( )
• Returns a list of dictionary’s pairs as tuples
• [Example]
• dic1 = {1: ‘one’, 2: ‘two’}
• dic1.items()
• => dict_items([(1, 'one'), (2, 'two')])
82
keys( )
• Returns list of the dictionary's keys
• [Example]
• dic1 = {1: ‘one’, 2: ‘two’}
• dic1.keys()
• => dict_keys([1, 2])
83
len( )
• Find the number of items in a dictionary
• [Example]
• dic1 = {1: ‘one’, 2: ‘two’}
• print (len(dic1))
• => 2
84
update( )
• Adds one dictionary’s key-values pairs to another. Duplicates
are removed.
• [Example]
• dic1 = {1: ‘one’, 2: ‘two’}
• dic2 = {1: ‘one’, 3: ‘three’}
• dic1.update(dic2)
• print (dic1)
• => {1: 'one', 2: 'two', 3: 'three'}
• print (dic2)
• #no change
• => {1: ‘one’, 3: ‘three’}
85
values( )
• Returns list of the dictionary's values
• [Example]
• dic1 = {1: ‘one’, 2: ‘two’}
• dic1.values()
• => dict_values(['one', 'two'])
86
End of 4
87