0% found this document useful (0 votes)
42 views75 pages

Kuliah 6 Alprog - Lists, Tuples, Sets, and Dictionaries

Lists are one of the four collection data types in Python. Lists are ordered and changeable collections that allow duplicate elements. A list is created using square brackets [], with comma-separated values of any data type. List elements can be accessed using indexes with square brackets, modified using slice operations, and iterated over using for loops. Lists are mutable, meaning their elements can be modified after the list is created.

Uploaded by

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

Kuliah 6 Alprog - Lists, Tuples, Sets, and Dictionaries

Lists are one of the four collection data types in Python. Lists are ordered and changeable collections that allow duplicate elements. A list is created using square brackets [], with comma-separated values of any data type. List elements can be accessed using indexes with square brackets, modified using slice operations, and iterated over using for loops. Lists are mutable, meaning their elements can be modified after the list is created.

Uploaded by

Azzahrah Yr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

LISTS, TUPLES, SETS,

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 are similar to strings, which are ordered sets of characters,


except that the elements of a list can have any type.

Lists and strings and other things that behave like ordered sets are
called sequences.

Python Programming Chapter 8 - Saad


3
Bani Mohammad
Lists
• The list is a most versatile datatype available in Python, which can be
written as a list of comma-separated values (items) between square
brackets. Good thing about a list that items in a list need not all have the
same type:
• Creating a list is as simple as putting different comma-separated values
between squere brackets. For example:
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];

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.

vocabulary = ["ameliorate", "castigate", "defenestrate"]


numbers = [17, 123]
empty = [ ]
print(vocabulary, numbers, empty)
['ameliorate', 'castigate', 'defenestrate'] [17, 123] [ ]

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.

Remember that the indices start at 0:


print(numbers[0])
numbers[1] = 5
The bracket operator can appear anywhere in an expression. When it appears on the left side of an
assignment, it changes one of the elements in the list, so the one-eth element of numbers, which used to be
123, is now 5.

Any integer expression can be used as an index:


>>> numbers[3-2]
5
>>> numbers[1.0]
TypeError: sequence index must be integer
If you try to read or write an element that does not exist, you get a runtime error:
>>> numbers[2] = 5
IndexError: list assignment index out of range

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:

['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]


As an exercise, write a loop that traverses the previous list and prints the length of
each element. What happens if you send an integer to len?

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:

>>> horsemen = ['war', 'famine', 'pestilence', 'death']


>>> 'pestilence' in horsemen
TRUE
>>> 'debauchery' in horsemen
FALSE

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:

>>> 'debauchery' not in horsemen


TRUE

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

for fruit in ["banana", "apple", "quince"]:


print("I like to eat " + fruit + "s!”)
The first example prints all the even numbers between one and nineteen. The second example expresses enthusiasm for
various fruits.

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']

With the slice operator we can update several elements at once:


>>> list = ['a', 'b', 'c', 'd', 'e', 'f']
>>> list[1:3] = ['x', 'y']
>>> print(list)
['a', 'x', 'y', 'd', 'e', 'f']

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']

>>> list[4:4] = ['e']


>>> print(list)
['a', 'b', 'c', 'd', 'e', 'f']

Python Programming Chapter 8 - Saad Bani Mohammad 13


Lists Deletion
Using slices to delete list elements can be awkward, and therefore error-prone. Python provides an
alternative that is more readable.
del removes an element from a list:
>>> a = ['one', 'two', 'three']
>>> del a[1]
>>> a
['one', 'three']

As you might expect, del handles negative indices and causes a runtime error if the index is out of
range.

You can use a slice as an index for del:


>>> list = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del list[1:5]
>>> print(list)
['a', 'f']
As usual, slices select all the elements up to, but not including, the second index.

Python Programming Chapter 8 - Saad Bani Mohammad 14


Updating Lists:
• You can update single or multiple elements of lists by giving the slice on the left-hand side
of the assignment operator, and you can add to elements in a list with the append()
method:
• Example:
list1 = ['physics', 'chemistry', 1997, 2000];
Print("Value available at index 2 : ”)
Print(list1[2]);
list1[2] = 2001;
Print("New value available at index 2 : ”)
Print(list1[2]);
• This will produce following result:
Value available at index 2 :
1997
New value available at index 2 :
2001
Delete List Elements:
• To remove a list element, you can use either the del statement if you know
exactly which element(s) you are deleting or the remove() method if you do
not know.
• Example:
list1 = ['physics', 'chemistry', 1997, 2000];
print(list1);
del list1[2];
Print("After deleting value at index 2 : ”)
Print(list1);
• This will produce following result:
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
Basic List Operations:
• Lists respond to the + and * operators much like strings; they mean concatenation
and repetition here too, except that the result is a new list, not a string.
• In fact, lists respond to all of the general sequence operations we used on strings in
the prior chapter :

Python Expression Results Description


len([1, 2, 3]) 3 Length

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition

3 in [1, 2, 3] TRUE Membership

for x in [1, 2, 3]: print x, 123 Iteration


List Operations
The + operator concatenates lists:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print(c)
[1, 2, 3, 4, 5, 6]

Similarly, the * operator repeats a list a given number of times:


>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

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!']

Python Expression Results Description


L[2] 'SPAM!' Offsets start at zero

L[-2] 'Spam' Negative: count from


the right
L[1:] ['Spam', 'SPAM!'] Slicing fetches sections
List Slices
The slice operations work on lists:

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


>>> list[1:3]
['b', 'c']

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

There are two possible states:

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

So the state diagram looks like this:

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]

Although this behaviour can be useful, it is sometimes unexpected or undesirable. In general, it is


safer to avoid aliasing when you are working with mutable objects. Of course, for immutable
objects, there's no problem. That's why Python is free to alias strings when it sees an opportunity
to economize.

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.“

The easiest way to clone a list is to use the slice operator:


>>> a = [1, 2, 3]
>>> b = a[:]
>>> print b
[1, 2, 3]
Taking any slice of a creates a new list. In this case the slice happens to consist of the whole list.

Now we are free to make changes to b without worrying about a:


>>> b[0] = 5
>>> print a
[1, 2, 3]

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

Or we can combine them:


>>> list[3][1]
20

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:

might be represented as:


>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix is a list with three elements, where each element is a row of the matrix. We can select an
entire row from the matrix in the usual way:
>>> matrix[1]
[4, 5, 6]
Or we can extract a single element from the matrix using the double-index form:
>>> matrix[1][1]
5
The first index selects the row, and the second index selects the column. Although this way of
representing matrices is common, it is not the only possibility. A small variation is to use a list of
columns instead of a list of rows. Later we will see a more thorough alternative using a dictionary.

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...']

An optional argument called a delimiter can be used to specify which characters to


use as word boundaries. The following example uses the string ai as the delimiter:
>>> string.split(song, 'ai')
['The r', 'n in Sp', 'n...']

Notice that the delimiter doesn't appear in the list.

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:

>>> list = ['The', 'rain', 'in', 'Spain...']


>>> string.join(list)
'The rain in Spain...‘

Like split, join takes an optional delimiter that is inserted between elements. The default delimiter
is a space.

>>> string.join(list, '_')


'The_rain_in_Spain...‘

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:

SN Function with Description


1 cmp(list1, list2)
Compares elements of both lists.
2 len(list)
Gives the total length of the list.
3 max(list)
Returns item from the list with max value.
4 min(list)
Returns item from the list with min value.
5 list(seq)
Converts a tuple into list.
SN Methods with Description
1 list.append(obj)
Appends object obj to list
2 list.count(obj)
Returns count of how many times obj occurs in list
3 list.extend(seq)
Appends the contents of seq to list
4 list.index(obj)
Returns the lowest index in list that obj appears
5 list.insert(index, obj)
Inserts object obj into list at offset index
6 list.pop(obj=list[-1])

Removes and returns last object or obj from list


7 list.remove(obj)

Removes object obj from list


8 list.reverse()

Reverses objects of list in place


9 list.sort([func])

Sorts objects of list, use compare func if given


Python - Tuples
• A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The only difference
is that tuples can't be changed ie. tuples are immutable and tuples use parentheses and lists use square
brackets.
• Creating a tuple is as simple as putting different comma-separated values and optionally you can put these
comma-separated values between parentheses also. For example:
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing:
tup1 = ();
To write a tuple containing a single value you have to include a comma, even though there is only one value:
tup1 = (50,);
• Like string indices, tuple indices start at 0, and tuples can be sliced, concatenated and so on.
Accessing Values in Tuples:
• To access values in tuple, use the square brackets for slicing along with the
index or indices to obtain value available at that index:
• Example:
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
Print("tup1[0]: ", tup1[0])
Print("tup2[1:5]: “, tup2[1:5])
• This will produce following result:
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Updating Tuples:
• Tuples are immutable which means you cannot update them or change
values of tuple elements. But we able able to take portions of an existing
tuples to create a new tuples as follows:
• Example:
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
tup3 = tup1 + tup2;
print tup3;
This will produce following result:
(12, 34.56, 'abc', 'xyz')
Delete Tuple Elements:
• Removing individual tuple elements is not possible. There is, of course,
nothing wrong with putting together another tuple with the undesired
elements discarded.
• To explicitly remove an entire tuple, just use the del statement:
• Example:
tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
print "After deleting tup : " print tup;
• This will produce following result.
('physics', 'chemistry', 1997, 2000)
After deleting tup : Traceback (most recent call last):
File "test.py", line 9, in <module> print tup;
NameError: name 'tup' is not defined
Basic Tuples Operations:
• Tuples respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new tuple,
not a string.
• In fact, tuples respond to all of the general sequence operations we used on
strings in the prior chapter :

Python Expression Results Description


len((1, 2, 3)) 3 Length
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
['Hi!'] * 4 ('Hi!', 'Hi!', 'Hi!', Repetition
'Hi!')
3 in (1, 2, 3) TRUE Membership
for x in (1, 2, 3): 123 Iteration
print x,
Indexing, Slicing, and Matrixes:
• Because tuples are sequences, indexing and slicing work the same way for
tuples as they do for strings.
• Assuming following input:
L = ('spam', 'Spam', 'SPAM!')

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

• Sets are used to store multiple items in a single variable.


• Set is one of 4 built-in data types in Python used to store collections of
data, the other 3 are List, Tuple, and Dictionary, all with different qualities
and usage.
• A set is a collection which is both unordered and unindexed.
• Sets are written with curly brackets.
Membuat SET

• thisset = {"apple", "banana", "cherry"}


print(thisset)

• 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

• thisset = {"apple", "banana", "cherry", "apple"}

print(thisset)
DICTIONARY
Lesson objectives

1. Describe the characteristics of the


dictionary data structure in Python
2. Perform basic operations with dictionaries
including creation, copying, updating, and
traversing
3. Use dictionaries in functions

Python Mini-Course: Lesson 16 58


The dictionary data structure

• In Python, a dictionary is mapping between a set of indices (keys) and a set


of values
• The items in a dictionary are key-value pairs

Python Mini-Course: Lesson 16 59


The dictionary data structure

• Keys can be any Python data type


• Because keys are used for indexing, they should be immutable
• Values can be any Python data type
• Values can be mutable or immutable

Python Mini-Course: Lesson 16 60


Creating a dictionary

eng2sp = dict()
print eng2sp

eng2sp['one'] = 'uno'
print eng2sp

eng2sp['two'] = 'dos'
print eng2sp

Python Mini-Course: Lesson 16 61


Creating a dictionary

eng2sp = {'one': 'uno', 'two': 'dos',


'three': 'tres'}
print eng2sp

•In general, the order of items in a dictionary is


unpredictable
•Dictionaries are indexed by keys, not integers

Python Mini-Course: Lesson 16 62


Dictionary indexing

print eng2sp['three']

print eng2sp['five']

* If the index is not a key in the dictionary,


Python raises an exception

Python Mini-Course: Lesson 16 63


Dictionary indexing

if 'five' in eng2sp:
print eng2sp['five']

print eng2sp.get('five')

Python Mini-Course: Lesson 16 64


The in operator

•Note that the in operator works differently for


dictionaries than for other sequences
•For offset indexed sequences (strings, lists, tuples), x in
y checks to see whether x is an item in the sequence
•For dictionaries, x in y checks to see whether x is a
key in the dictionary

Python Mini-Course: Lesson 16 65


Keys and values

• The keys method returns a list of the keys in


a dictionary
print eng2sp.keys()

• The values method returns a list of the


values
print eng2sp.values()

Python Mini-Course: Lesson 16 66


Keys and values

• The items method returns a list of tuple


pairs of the key-value pairs in a dictionary
print eng2sp.items()

Python Mini-Course: Lesson 16 67


Example: histogram.py
def histogram(seq):
d = dict()
for element in seq:
if element not in d:
d[element] = 1
else:
d[element] += 1
return d

h = histogram('brontosaurus')
print h

Python Mini-Course: Lesson 16 68


Example: histogram2.py

Add the following code to histogram.py:

def print_hist(hist):
for key in hist:
print key, hist[key]

h = histogram('brontosaurus')
print_hist(h)

5/10/09 Python Mini-Course: Lesson 16 69


Example: histogram2.py

Change the print_hist function:

def print_hist(hist):
for key, value in hist:
print key, value

h = histogram('brontosaurus')
print_hist(h)

5/10/09 Python Mini-Course: Lesson 16 70


Sorting the keys

Change the print_hist function:

def print_hist(hist):
keys = hist.keys()
keys.sort()
for key in keys:
print key, hist[key]

h = histogram('brontosaurus')
print_hist(h)

5/10/09 Python Mini-Course: Lesson 16 71


Using lists as values: invert.py

• Add the following code to histogram.py:


def invert_dict(d):
inv = dict()
for key in d:
val = d[key]
if val not in inv:
inv[val] = [key]
else:
inv[val].append(key)
return inv

5/10/09 Python Mini-Course: Lesson 16 72


Using lists as values: invert.py

• Add the following code to histogram.py:

hist = histogram('parrot')
print hist
inverted = invert_dict(hist)
print inverted

5/10/09 Python Mini-Course: Lesson 16 73


Using tuples as keys: troupe.py

troupe = {('Cleese', 'John'): [1,2,3],


('Chapman', 'Graham'): [4,5,6],
('Idle', 'Eric'): [7,8,9],
('Jones', 'Terry'): [10,11,12],
('Gilliam', 'Terry'):
[13,14,15,16,17,18],
('Palin', 'Michael'): [19,20]}

for last, first in troupe:


print first, last, troupe[last, first]

5/10/09 Python Mini-Course: Lesson 16 74


THANK YOU !!!
STAY SAFE, STAY AT HOME

You might also like