Kuliah 6 Alprog - Lists, Tuples, Sets, and Dictionaries
Kuliah 6 Alprog - Lists, Tuples, Sets, and Dictionaries
and DICTIONARIES
Kuliah 4 – Algoritma dan Pemrograman
Python Collections (Arrays)
There are four collection data types in the Python programming language:
• List is a collection which is ordered and changeable. Allows duplicate
members.
• Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
• Set is a collection which is unordered and unindexed. No duplicate
members.
• Dictionary is a collection which is unordered and changeable. No duplicate
members.
Lists
A list is an ordered set of values, where each value is identified by an
index. The values that make up a list are called its elements.
Lists and strings and other things that behave like ordered sets are
called sequences.
Like string indices, list indices start at 0, and lists can be sliced, concatenated
and so on.
List Values
There are several ways to create a new list; the simplest is to enclose the elements in square brackets ([ and ]):
[10, 20, 30, 40]
["spam", "bungee", "swallow"]
The first example is a list of four integers. The second is a list of three strings. The elements of a list don't have to be
the same type. The following list contains a string, a float, an integer, and another list:
["hello", 2.0, 5, [10, 20]]
With all these ways to create lists, it would be disappointing if we couldn't assign list values to variables or pass lists
as parameters to functions. We can.
5
Accessing Values in Lists (elements):
• To access values in lists, use the square brackets for slicing along with the
index or indices to obtain value available at that index:
• Example:
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
Print("list1[0]: ", list1[0])
Print("list2[1:5]: ", list2[1:5])
• This will produce following result:
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Accessing Elements (Cont)
The syntax for accessing the elements of a list is the same as the syntax for accessing the characters of a
string--the bracket operator ([ ]). The expression inside the brackets specifies the index.
7
Accessing Elements (Cont…)
If an index has a negative value, it counts backward from the end of the list:
>>> numbers[-1]
5
>>> numbers[-2]
17
>>> numbers[-3]
IndexError: list index out of range
numbers[-1] is the last element of the list, numbers[-2] is the second to last, and numbers[-3] doesn't exist.
It is common to use a loop variable as a list index.
horsemen = ["war", "famine", "pestilence", "death"]
i=0
while i < 4:
print(horsemen[i])
i += 1
This while loop counts from 0 to 4. When the loop variable i is 4, the condition fails and the loop terminates. So
the body of the loop is only executed when i is 0, 1, 2, and 3.
Each time through the loop, the variable i is used as an index into the list, printing the i-eth element. This pattern
of computation is called a list traversal.
8
List Length
The function len() returns the length of a list. It is a good idea to use this value as the upper bound of a loop
instead of a constant. That way, if the size of the list changes, you won't have to go through the program
changing all the loops; they will work correctly for any size list:
horsemen = ["war", "famine", "pestilence", "death"]
i=0
while i < len(horsemen):
print horsemen[i]
i=i+1
The last time the body of the loop is executed, i is len(horsemen) - 1, which is the index of the last element.
When i is equal to len(horsemen), the condition fails and the body is not executed, which is a good thing,
because len(horsemen) is not a legal index.
Although a list can contain another list, the nested list still counts as a single element. The length of this list
is four:
9
List Membership
in is a boolean operator that tests membership in a sequence. We used it in Chapter 7 with
strings, but it also works with lists and other sequences:
Since "pestilence" is a member of the horsemen list, the in operator returns true. Since
"debauchery" is not in the list, in returns false.
We can use the not in combination with in to test whether an element is not a member of a
list:
10
List and for Loops
The for loop we saw in Chapter 7 also works with lists. The generalized syntax of a for loop is:
for VARIABLE in LIST:
BODY
This statement is equivalent to:
i=0
while i < len(LIST):
VARIABLE = LIST[i]
BODY
i=i+1
The for loop is more concise because we can eliminate the loop variable, i. Here is the previous loop written with a for loop.
for horseman in horsemen:
print horseman
It almost reads like English: "For (every) horseman in (the list of) horsemen, print (the name of the) horseman.“ Any list
expression can be used in a for loop:
for number in range(20):
if number % 2 == 0:
print number
11
Lists are Mutable
Unlike strings, lists are mutable, which means we can change their elements. Using
the bracket operator on the left side of an assignment, we can update one of the
elements:
>>> fruit = ["banana", "apple", "quince"]
>>> fruit[0] = "pear"
>>> fruit[-1] = "orange"
>>> print(fruit)
['pear', 'apple', 'orange']
12
Lists are Mutable (Cont…)
We can also remove elements from a list by assigning the empty list to them:
>>> list = ['a', 'b', 'c', 'd', 'e', 'f']
>>> list[1:3] = []
>>> print(list)
['a', 'd', 'e', 'f']
And we can add elements to a list by squeezing them into an empty slice at the desired location:
>>> list = ['a', 'd', 'f']
>>> list[1:1] = ['b', 'c']
>>> print(list)
['a', 'b', 'c', 'd', 'f']
As you might expect, del handles negative indices and causes a runtime error if the index is out of
range.
The first example repeats [0] four times. The second example repeats the list [1, 2, 3] three
times.
18
Indexing, Slicing, and Matrixes:
• Because lists are sequences, indexing and slicing work the same way for lists as they do
for strings.
• Assuming following input:
L = ['spam', 'Spam', 'SPAM!']
>>> list[:4]
['a', 'b', 'c', 'd']
>>> list[3:]
['d', 'e', 'f']
>>> list[:]
['a', 'b', 'c', 'd', 'e', 'f']
20
Objects and Values
If we execute these assignment statements,
a = "banana"
b = "banana"
we know that a and b will refer to a string with the letters "banana". But we can't tell whether they point to
the same string.
In one case, a and b refer to two different things that have the same value. In the second case, they refer to
the same thing. These "things" have names--they are called objects. An object is something a variable can
refer to.
Every object has a unique identifier, which we can obtain with the id function. By printing the identifier of
a and b, we can tell whether they refer to the same object.
>>> id(a)
135044008
>>> id(b)
135044008
21
Objects and Values (Cont…)
In fact, we get the same identifier twice, which means that Python only created one string,
and both a and b refer to it.
Interestingly, lists behave differently. When we create two lists, we get two objects:
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> id(a)
135045528
>>> id(b)
135041704
a and b have the same value but do not refer to the same object.
22
Aliasing
Since variables refer to objects, if we assign one variable to another, both variables refer to the
same object:
>>> a = [1, 2, 3]
>>> b = a
In this case, the state diagram looks like this:
Because the same list has two different names, a and b, we say that it is aliased. Changes made
with one alias affect the other:
>>> b[0] = 5
>>> print a
[5, 2, 3]
23
Cloning Lists
If we want to modify a list and also keep a copy of the original, we need to be able to make a copy of
the list itself, not just the reference. This process is sometimes called cloning, to avoid the ambiguity of
the word "copy.“
As an exercise, draw a state diagram for a and b before and after this change.
24
List Parameters
Passing a list as an argument actually passes a reference to the list, not a copy of the list. For
example, the function head takes a list as a parameter and returns the first element:
def head(list):
return list[0]
Here's how it is used:
>>> numbers = [1, 2, 3]
>>> head(numbers)
1
The parameter list and the variable numbers are aliases for the same object. The state
diagram looks like this:
25
List Parameters (Cont…)
Since the list object is shared by two frames, we put it between them.
If a function modifies a list parameter, the caller sees the change. For example, delete_head removes the first element
from a list:
def delete_head(list):
del list[0]
Here's how delete_head is used:
>>> numbers = [1, 2, 3]
>>> delete_head(numbers)
>>> print numbers
[2, 3]
If a function returns a list, it returns a reference to the list. For example, tail returns a list that contains all but the first
element of the given list:
def tail(list):
return list[1:]
Here's how tail is used:
>>> numbers = [1, 2, 3]
>>> rest = tail(numbers)
>>> print rest
[2, 3]
Because the return value was created with the slice operator, it is a new list. Creating rest, and any subsequent changes
to rest, have no effect on numbers.
26
Nested Lists
A nested list is a list that appears as an element in another list. In this list, the three-eth is a nested
list:
>>> list = ["hello", 2.0, 5, [10, 20]]
If we print list[3], we get [10, 20]. To extract an element from the nested list, we can proceed in
two steps:
>>> elt = list[3]
>>> elt[0]
10
Bracket operators evaluate from left to right, so this expression gets the three-eth element of list
and extracts the one-eth element from it.
27
Matrices
Nested lists are often used to represent matrices. For example, the matrix:
28
Strings and Lists
Two of the most useful functions in the string module involve lists of strings. The
split function breaks a string into a list of words. By default, any number of white
space characters is considered a word boundary:
>>> import string
>>> song = "The rain in Spain..."
>>> string.split(song)
['The', 'rain', 'in', 'Spain...']
29
Strings and Lists (Cont…)
The join function is the inverse of split. It takes a list of strings and concatenates the elements with
a space between each pair:
Like split, join takes an optional delimiter that is inserted between elements. The default delimiter
is a space.
As an exercise, describe the relationship between string.join(string.split(song)) and song. Are they
the same for all strings? When would they be different?
30
Contoh
Questions
Q1. Creation of list and changing value of any one element, also display the length of list.
Q2. Create a list and append two elements in it.
Q3. Create a list and sort it.
Q4. Create a list of numbers and print sum of all the elements.
Q5. Program to compare elements of list.
Q6. Program to find maximum and minimum of list.
Q7. Count the occurrence of element in list.
Q8. Reverse a list.
Q9.Write a loop that traverses the previous list and prints the length of each element. What
happens if you send an integer to len?
Q10. Describe the relationship between string.join(string.split(song)) and song. Are they the
same for all strings? When would they be different? (song is a string)
Built-in List Functions & Methods:
Python
Results Description
Expression
L[2] 'SPAM!' Offsets start at zero
L[-2] 'Spam' Negative: count from the right
L[1:] ['Spam', 'SPAM!'] Slicing fetches sections
No Enclosing Delimiters:
• Any set of multiple objects, comma-separated, written without identifying
symbols, i.e., brackets for lists, parentheses for tuples, etc., default to
tuples, as indicated in these short examples:
print 'abc', -4.24e93, 18+6.6j, 'xyz';
u, v = 1, 2;
print "Value of u , v : ", u,v;
print var;
• This will reduce following result:
abc -4.24e+93 (18+6.6j) xyz
Value of u , v : 1 2
Built-in Tuple Functions:
SN Function with Description
1 cmp(tuple1, tuple2)
Compares elements of both tuples.
2 len(tuple)
Gives the total length of the tuple.
3 max(tuple)
Returns item from the tuple with max value.
4 min(tuple)
Returns item from the tuple with min value.
5 tuple(seq)
Converts a list into tuple.
Example 1
• Create a tuple containing the names of five countries and display the
whole tuple. Ask the user to enter one of the countries that have been
shown to them and then display the index number (i.e. position in the list)
of that item in the tuple.
Example 2
• Add to the previous program to ask the user to enter a number and display
the country in that position.
Example 3
• Create a list of two sports. Ask the user what their favourite sport is and
add this to the end of the list. Sort the list and display it.
Example 4
• Create a list of six school subjects. Ask the user which of these subjects
they don’t like. Delete the subject they have chosen from the list before
you display the list again.
Example 5
• Enter a list of ten colours. Ask the user for a starting number between 0
and 4 and an end number between 5 and 9. Display the list for those
colours between the start and end numbers the user input.
Example 6
• Create a list of four three-digit numbers. Display the list to the user,
showing each item from the list on a separate line. Ask the user to enter a
three-digit number. If the number they have typed in matches one in the
list, display the position of that number in the list, otherwise display the
message “That is not in the list”.
Example 7
• Ask the user to enter the names of three people they want to invite to a
party and store them in a list. After they have entered all three names, ask
them if they want to add another. If they do, allow them to add more
names until they answer “no”. When they answer “no”, display how many
people they have invited to the party.
Example 8
• Change program on Example 7 so that once the user has completed their
list of names, display the full list and ask them to type in one of the names
on the list. Display the position of that name in the list. Ask the user if they
still want that person to come to the party. If they answer “no”, delete that
entry from the list and display the list again.
Example 9
• Create a list containing the titles of four TV programmes and display them
on separate lines. Ask the user to enter another show and a position they
want it inserted into the list. Display the list again, showing all five TV
programmes in their new positions.
Example 10
• Create an empty list called “nums”. Ask the user to enter numbers. After
each number is entered, add it to the end of the nums list and display the
list. Once they have entered three numbers, ask them if they still want the
last number they entered saved. If they say “no”, remove the last item
from the list. Display the list of numbers.
Example 11
• Ask the user to enter four of their favourite foods and store them in a
dictionary so that they are indexed with numbers starting from 1. Display
the dictionary in full, showing the index number and the item. Ask them
which they want to get rid of and remove it from the list. Sort the
remaining data and display the dictionary.
PYTHON SETS
• Unordered means that the items in a set do not have a defined order.
• Set items can appear in a different order every time you use them, and
cannot be referred to by index or key.
• Sets are unchangeable, meaning that we cannot change the items after the
set has been created.
• Once a set is created, you cannot change its items, but you can add new
items.
Duplicates Not Allowed
print(thisset)
DICTIONARY
Lesson objectives
eng2sp = dict()
print eng2sp
eng2sp['one'] = 'uno'
print eng2sp
eng2sp['two'] = 'dos'
print eng2sp
print eng2sp['three']
print eng2sp['five']
if 'five' in eng2sp:
print eng2sp['five']
print eng2sp.get('five')
h = histogram('brontosaurus')
print h
def print_hist(hist):
for key in hist:
print key, hist[key]
h = histogram('brontosaurus')
print_hist(h)
def print_hist(hist):
for key, value in hist:
print key, value
h = histogram('brontosaurus')
print_hist(h)
def print_hist(hist):
keys = hist.keys()
keys.sort()
for key in keys:
print key, hist[key]
h = histogram('brontosaurus')
print_hist(h)
hist = histogram('parrot')
print hist
inverted = invert_dict(hist)
print inverted