You are on page 1of 28

1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

CS 1101 Programming Fundamentals - AY2022-T2


Dashboard / My courses /
CS 1101 - AY2022-T2 / 23 December - 29 December /
Discussion Forum Unit 7 /
Discussion Unit 7

 Search forums

Discussion Forum Unit 7


Discussion Unit 7

Settings

Display replies in nested form

The cut-off date for posting to this forum is reached so you can no longer post to it.

Discussion Unit 7
by Leonidas Papoulakis (Instructor) - Wednesday, 10 November 2021, 7:12 AM

Describe how tuples can be useful with loops over lists and dictionaries, and give Python code examples. Create your own code
examples. Do not copy them from the textbook or any other source. 

Your descriptions and examples should include the following: the zip function, the enumerate function, and the items method. 

51 words

Permalink

Re: Discussion Unit 7


by Samrawi Berhe - Sunday, 26 December 2021, 6:39 AM

Discussion_Forum_Unit_7

1.     
Describe
how tuples can be useful with loops over lists and dictionaries
and give Python code examples. Your
descriptions and examples should include
the following: the zip function, the enumerate function, and the items method.

Answer

Description: -

A dictionary uses the hash values to


store and lookup the key-value pair. However, dictionaries are mutable; they
cannot be
used as keys, but they can be used as values. So, a hash is a
function that takes any value and returns an integer. These
numbers, known as hash
values, are used by dictionaries to store and lookup key-value pairs. This way
is the only way to
traverse using a loop. 

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 1/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

If the keys are immutable, this approach works perfectly.


However, if the keys are changeable, such as in a list and dictionary,
horrible
things happen. When you construct a key-value pair, for example, Python hashes
the key and saves it in the right
place. If you change the key and hash it
again, it will take you to a new location. In that situation, you may have two
entries for
the same key, or you may be unable to locate a key. In either case,
the dictionary would not function properly.

That
is why keys must be hashable and changeable types. Tuples are like lists in
that the values can be of any type, and they
are indexed by integers. The key
distinction is that tuples are immutable. Therefore, using tuples is the simplest approach
to
solving this constraint. This is because a tuple is a sequence of values. (Downey A, 2015, pp. 106-115). There are some built-in
functions or methods in both the
tuple and dictionary data structures that are designed to iterate over lists or
dictionaries. A
few of them are as follows.

Illustration: -

1.      items() method   is used in Dictionary

The dict.items() method returns a list


of tuple pairs (Keys, Values) in the dictionary. The following is a sample code
to illustrate
the use of items() method which iterates through a dictionary and returns a key-value pair
as a list each time.

The code is as below

The output is as below

2.     
The zip() Function

The zip() function


accepts two or more which able to iterate objects as parameters and produces a
tuple iterator. An iterator is
a value-containing object with a countable
number of values. The number of parameters passed to the zip function
influences
the number of items in the tuples formed and the number of items in
the objects supplied as arguments that are not equal.

The Codes
are below

The output of the above code is

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 2/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

3. The
enumerate() Function

The for loop-based enumerate() function accepts a sequence that is able to iterate
(e.g strings, lists, tuples, etc.) and produces
a series of tuples containing an
index and their corresponding items.

The code is below: -

The output of the above code

482 words
Tags:
Discussion Forum Unit 7

all_codes.py
Permalink Show parent

Re: Discussion Unit 7


by Ahmet Yilmazlar - Monday, 27 December 2021, 8:39 AM

explanation is clear and precise. The examples you present are also very nice
13 words

Permalink Show parent

Re: Discussion Unit 7


by Samrawi Berhe - Monday, 27 December 2021, 12:04 PM

Thank you, Ahmet, for your comments.


6 words

Permalink Show parent

Re: Discussion Unit 7


by Siphumelelise Ntshwenyese - Monday, 27 December 2021, 8:55 AM

Samrawi, I enjoyed reading this and your examples were your own, with lots of comments, well done
17 words

Permalink Show parent

Re: Discussion Unit 7


by Samrawi Berhe - Monday, 27 December 2021, 12:05 PM

Thank you, Siphumelelise, for your appreciation and comments.
8 words

Permalink Show parent

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 3/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

Re: Discussion Unit 7


by Wilmer Portillo - Monday, 27 December 2021, 4:13 PM

Hi Samrawi,

Thank you very much for your discussion as always very complete and on point. Always going beyond and above. You
postings always clears up doubts I may have. Your illustrations and comments are on track. Keep up the awesome job!
42 words

Permalink Show parent

Re: Discussion Unit 7


by Fouad Tarabay - Monday, 27 December 2021, 4:40 PM

Hello Samrawi, well done in the discussion, everything was clear and you gave a suitable examples for each output.
19 words

Permalink Show parent

Re: Discussion Unit 7


by Crystal Noralez - Wednesday, 29 December 2021, 10:39 AM

Hi,

Well done of a very clear and understandable assignment.


10 words

Permalink Show parent

Re: Discussion Unit 7


by Janelle Bianca Cadawas Marcos - Wednesday, 29 December 2021, 12:53 PM

I always look forward to seeing what you post here, it's always easy to understand and in-depth. Excellent job!
19 words

Permalink Show parent

Re: Discussion Unit 7


by Stephen Chuks - Wednesday, 29 December 2021, 1:13 PM

Your work is clear and precise. The codes are also understandable. And your examples makes it very much easy for people
to understand the discussion better

26 words

Permalink Show parent

Re: Discussion Unit 7


by Simon Njoroge - Wednesday, 29 December 2021, 2:21 PM

I like your explanation, always on point and makes it very clear for us to understand. Thank you for your intensive
explanation and input.
24 words

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 4/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

Permalink Show parent

Re: Discussion Unit 7


by Peter Odetola - Wednesday, 29 December 2021, 10:45 PM

Well define terms and illustrated explanations. Thanks Samrawi


8 words

Permalink Show parent

Re: Discussion Unit 7


by Fouad Tarabay - Sunday, 26 December 2021, 7:13 AM

Tuples can be useful with loops over lists is that we can iterate over two lists with a single for loop and that could be done by
transforming the two lists into tuples using zip() method that returns a collection of tuples formed by these lists.

Example:

Code:

List1 = [1,2,3,4]

List2 = [5,6,7,8]

ZipList3 = list(zip(List1,List2))

print("The zip() method produces: ",ZipList3)

print("After iterating with one loop: ")

for i,j in ZipList3:

print(i," ",j)

output:

The zip() method produces: [(1, 5), (2, 6), (3, 7), (4, 8)]

After iterating with one loop:

1 5

2 6

3 7

4 8

In the above code the zip() method transforms our 2 lists into list of tuples and each tuple contains an element from the first
list and the second, we iterate using only one for loop on the list of tuples which makes it more easier than using 2 loops to
iterate over each list alone.

Tuples can be useful with loops over dictionaries by transforming each element (key,value) in the dictionary into collection of
tuples by the method d.items() where d is the dictionary and items() is a method used on the dictionary d which returns a
collection of tuples formed by the dictionary keys and values in the following form (key,value) then we can iterate over it with a
for loop.

Example:

Code:

dictionary = {"Hello":"world","Python":"Programming","age":19,"key":"val"}

print("List of (key,values) formed by list(dictionary.items()):")

print(list(dictionary.items()))

print("We can also iterate over dictionary.items():")

for key,val in dictionary.items():

print("key: ",key," val: ",val)


output:

List of (key,values) formed by list(dictionary.items()):

[('Hello', 'world'), ('Python', 'Programming'), ('age', 19), ('key', 'val')]

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 5/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

We can also iterate over dictionary.items():

key: Hello val: world

key: Python val: Programming

key: age val: 19

key: key val: val

In the above code an iteration over dictionary was easier by assigning a variable name key to the keys in the dictionary and a
variable named val to the values in the dictionary using a single for loop items() method.
325 words

Permalink Show parent

Re: Discussion Unit 7


by Samrawi Berhe - Monday, 27 December 2021, 2:46 AM

Hi, Fouad, your explanation is clear and precise. The examples you present are also very nice. But I noticed that you failed
to give one more example since the assignment was to provide three examples. You could have used for example the
enumerate() built-in function.
45 words

Permalink Show parent

Re: Discussion Unit 7


by Ahmet Yilmazlar - Monday, 27 December 2021, 8:39 AM

explanation is clear and precise. The examples you present are also very nice
13 words

Permalink Show parent

Re: Discussion Unit 7


by Siphumelelise Ntshwenyese - Monday, 27 December 2021, 8:53 AM

Fouad, thank you for your post, it was a pleasure to read, well done.
14 words

Permalink Show parent

Re: Discussion Unit 7


by Wilmer Portillo - Monday, 27 December 2021, 4:15 PM

Hi Fouad,

Thanks you for your contribution. You explanation helped greatly in understanding the process of your discussion. Keep it
up!
21 words

Permalink Show parent

Re: Discussion Unit 7


by Peter Odetola - Wednesday, 29 December 2021, 10:49 PM

Hello Fouad,

Your presentation is good, clear, informative and interactive.


10 words

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 6/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

Permalink Show parent

Re: Discussion Unit 7


by Ahmet Yilmazlar - Sunday, 26 December 2021, 8:16 AM

Tuples are immutable lists and their immutability property is what makes them useful in iterating over lists and dictionaries.
Tuples can be used either as keys or values in a dictionary whereas lists and dictionaries can only be used as values in a
dictionary.

There some built-in functions or methods in both the tuple and dictionary data structures that are designed to iterate over lists
or dictionaries. A few of such as:

Dictionary items () method

The dict.items () method returns alist of tuples pairs (keys, Values) in the dictionary.

The following is a sample code to illustrate the use of items() method which iterates through a dictionary and returns a key
value pair as a list each time:

Code:

==============================

# the dictionary below contains students' names and their ages.

std_age = {'Max': 18, 'Chaleb':16, 'Jessica':17, 'James':19}

print("Students Name: %s" % list(std_age.items()))

Output:

==============================

Students Name: [('Max', 18), ('Chaleb', 16), ('Jessica', 17), ('James', 19)]

[Program finished]

The zip() function

The zip() function take two or more iterable objects as arguments and returns an iterator of tuples. An iterator is an object that
contains countable number of values. The number of arguments supplied in a zip function determines the number of items in
the tuples vreated. And where the items in the objects supplied as arguments are not equal.

code

================

# list of students' names

std_name = (‘’ Dave’’, ‘’ Evelyn’’, ‘’Alex’’, ‘’Steve’’, ‘’Christabel’’ )

#list of the students ‘ İD

std_id = [ ‘’012’’, ‘’031’’, ‘’026’’, ‘’009’’, ‘’014’’ ]

print(type(std_id))

#list of students' average performance

std_avg = [81.26, 74.84, 91.45, 64.28, 92.60]

#using zip() function

std_info = list(zip(std_name, std_id, std_avg))



print(std_info)

Output:

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 7/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

==============================

[('Dave', '012', 81.26), ('Evelyn', '031', 74.84), ('Alex', '026', 91.45), ('Steve', '009', 64.28), ('Christabel', '014', 92.6)]

[Program finished]

The enumerate() Function

The enumerate() function with a for loop takes an iterable sequence (e.g.strings, lists, tuples etc.) and returns a sequence of
tuples containing index and their corresponding elements.

Code:

==============================

std_name = ("Dave", "Evelyn", "Alex", "Steve", "Christabel"for index in enumerate(std_name):

print(index)

Output:

==============================

(0, 'Dave')

(1, 'Evelyn')

(2, 'Alex')

(3, 'Steve')

(4, 'Christabel')

[Program finished]

references:

Downey, A. (2015). Think python, How to think like a computer scientist


362 words

Permalink Show parent

Re: Discussion Unit 7


by Samrawi Berhe - Monday, 27 December 2021, 2:53 AM

Hi, Ahmet, your explanations and examples are great. The examples you present are also clear to understand. I also
appreciate the way you present the illustrations. Keep it up!
29 words

Permalink Show parent

Re: Discussion Unit 7


by Siphumelelise Ntshwenyese - Monday, 27 December 2021, 8:48 AM

Ahmet, your explanation was a pleasure to read, you provided your own examples too, well done.
16 words

Permalink Show parent


Re: Discussion Unit 7
by Wilmer Portillo - Monday, 27 December 2021, 4:16 PM

Hi Ahmet,

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 8/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

Thank yo very much for your contribution. Very complete and well structured work. Thank you!
17 words

Permalink Show parent

Re: Discussion Unit 7


by Fouad Tarabay - Monday, 27 December 2021, 4:42 PM

Hi Ahmet,

your explanation was done very well I was so exciting in reading your discussion examples, it was very clear and
informative.
23 words

Permalink Show parent

Re: Discussion Unit 7


by Siphumelelise Ntshwenyese - Sunday, 26 December 2021, 12:31 PM

To iterate over all elements of a hypothetical diction mary you just need one method .

hypothetical_dictionary.items()

Also, it's easier to iterate two things when using a tuple for example after the line break I am looking for both myKey and
myValue

The second thing that is awesome about tuples is that you can iterate two lists together using a function called zip()

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 9/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

Another interesting function is the enumerate function, it lets you create an enumerable object. This allows you to get an index
of an element while iterating over a list.

92 words

Permalink Show parent

Re: Discussion Unit 7


by Samrawi Berhe - Monday, 27 December 2021, 3:02 AM

Hi, Siphumelelise, the explanations are short, easy to understand, and precise. The illustrations are also great and you
covered all the questions as well. But it would be more helpful if you had added the outputs so as to understand your
code is working as you explained.
47 words

Permalink Show parent

Re: Discussion Unit 7


by Siphumelelise Ntshwenyese - Monday, 27 December 2021, 8:45 AM

Thank you Samrawi


3 words

Permalink Show parent

Re: Discussion Unit 7


by Ahmet Yilmazlar - Monday, 27 December 2021, 8:40 AM

yours explanation is clear and precise. The examples you present are also very nice
14 words

Permalink Show parent


Re: Discussion Unit 7
by Siphumelelise Ntshwenyese - Monday, 27 December 2021, 8:46 AM

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 10/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

Thank you Ahmet


3 words

Permalink Show parent

Re: Discussion Unit 7


by Stephen Chuks - Wednesday, 29 December 2021, 1:23 PM

Short and precise. And your code examples are understandable and clear. Good job.

13 words

Permalink Show parent

Re: Discussion Unit 7


by Simon Njoroge - Wednesday, 29 December 2021, 2:23 PM

Very well put. You have given relevant examples and explanation on the given questions. Your positive input in the
discussion have influenced the class positively. Keep it up.
28 words

Permalink Show parent

Re: Discussion Unit 7


by Peter Odetola - Wednesday, 29 December 2021, 10:54 PM

Hi, Siphumelelise

Aside from the clear illustrative work, your comments also guide in clarity and understanding.
16 words

Permalink Show parent

Re: Discussion Unit 7


by Simon Njoroge - Monday, 27 December 2021, 9:35 AM

Tuples can be useful with loops over lists and dictionaries. Loops normally take less time to execute and takes less space to
store. There are therefore more useful as opposed to lists and dictionaries.

We use round brackets in making tuples as opposed to square brackets in lists as i have illustrated in the examples below. I
have also demonstrated that one can use zip function to join both lists and tuples.

zipping 

https://my.uopeople.edu/pluginfile.php/1521290/mod_forum/post/15264999/zipping%20tuples.py

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 11/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

enumerate
https://my.uopeople.edu/pluginfile.php/1521290/mod_forum/post/15264999/enumerate.py

Adding items in lists and dictionaries as opposed to tuples


Dictionaries and lists are mutable , meaning they can be changed and amended. Tuples are however immutable and therefore
cannot be amended . This makes them more useful in developing a software since they enable the developer to avoid errors in
development by making unnecessary  amendments. 

Below is a prove of change of items in lists and dictionaries as opposed to tuples.

Amendment of dictionaries 
https://my.uopeople.edu/pluginfile.php/1521290/mod_forum/post/15264999/amend%20dictionary.py

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 12/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

Tuples cannot be amended

As I have indicated above , tuples cannot be amended. Below is a script and image with explanation on the same. 
https://my.uopeople.edu/pluginfile.php/1521290/mod_forum/post/15264999/items%20on%20lists.py

178 words

Permalink Show parent


Re: Discussion Unit 7


by Janelle Bianca Cadawas Marcos - Wednesday, 29 December 2021, 12:52 PM

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 13/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

Good job. This topic is a little confusing to me but I think I'm getting the hang of it. You should fix your formatting a little
more, the images you added for you examples are really big on desktop, it makes it difficult to read. Would be nice if you
included a more descriptive reason of why they're more useful.
60 words

Permalink Show parent

Re: Discussion Unit 7


by Wilmer Portillo - Monday, 27 December 2021, 1:53 PM

Discussion Assignment Unit 6:

Describe how tuples can be useful with loops over lists and dictionaries, and give Python code examples. Create your own
code examples. Do not copy them from the textbook or any other source. 
Your descriptions and examples should include the following: the zip function, the enumerate function, and the items method. 

Explanation:

Tuples are very essential and are very useful to store related attributes in a single object without creating a custom class or
parallel list.
The ‘zip’ function, as it names relays, is used to zip 2 lists together, it is an iterator of tuples where the first item in each
passed iterator is paired together.
The ‘enumerate’ function assigns indices to individual elements of list and it can be used instead of the ‘for’ loop. This is so
because this function can iterate over the index of an item and the item itself. This specific function also makes a cleaner
code as it uses fewer lines.
The ‘items’ method takes no parameters and is used to return the list with all dictionary keys and values.

Example A: In the below example it can be seen that tuples can be relevant when used with loops over dictionaries. In order
to iterate over the dictionary elements the o.items() method can be used to return the collection of tuples.

Input:

Output:

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 14/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

Example B: Tuples can also be used with loops over lists as it can iterate two lists (together) in one loop using the ‘zip’
function that in the following example will return the collection of tuples ‘m,n’.

Input:

Output:

References:

Downey, A. (2015). Think Python: How to think like a computer scientist. Green Tea Press. This book is licensed under Creative
Commons Attribution-NonCommercial 3.0 Unported (CC BY-NC 3.0).

297 words

Permalink Show parent

Re: Discussion Unit 7


by Fouad Tarabay - Monday, 27 December 2021, 4:48 PM

Hello Wilmer, your explanation was great, I liked how you explained each method on its own at first and then state the

examples. There is one thing missing that you could have included an example for the ‘enumerate’ method, but in general,
everything was good, keep it up!
48 words

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 15/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

Permalink Show parent

Re: Discussion Unit 7


by Juan Duran Solorzano - Tuesday, 28 December 2021, 10:46 PM

Dear Wilmer,

Well explained, clear, and concise with examples easy to follow.

Your examples helped me to fully understand some concepts I had some difficulties to understand.

What do you think are the pros and cons to use Tuples over dictionaries and lists?

Kind regards

Juan Carlos
47 words

Permalink Show parent

Re: Discussion Unit 7


by Janelle Bianca Cadawas Marcos - Wednesday, 29 December 2021, 12:48 PM

Nicely done, everything was well explained in a short way. I wasn't really sure for this topic, but this helped me understand
a little better. Thanks.
26 words

Permalink Show parent

Re: Discussion Unit 7


by Crystal Noralez - Tuesday, 28 December 2021, 9:45 AM

Discussion Forum Unit 7

Describe how tuples can be useful with loops over lists and dictionaries, and give Python code examples. Create your own
code examples. Do not copy them from the textbook or any other source. Your descriptions and examples should include the
following: the zip function, the enumerate function, and the items method.

Tuples are generated in Python using parenthesis. In a dictionary, tuples can be used as keys or values. They also have the
property of immutability, which makes them useful for iterating over lists and dictionaries.

Code:

print('===================Example 1, Dictionary==================')

student_data = [('Darlyn', 100), ('Angel', 80), ('Tiffany', 65),('Memory', 75)]

for (students, grades) in student_data

print(student, 'have', graded, 'marks out of a possible 100.')

print('')

print('===============Example 2, Zip function================')

student_list = ['Darlyn', 'Angel', 'Tiffany', 'Memory']



grades = [100, 80, 65, 75]

for (students_names, grades) in zip(students_list, grades):

print(student_name, 'have', grades, 'marks out of a possible 100.')

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 16/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

print('')

print('===================Example 3, Enumerate===================')

for (index, students_names) in enumerate(student_list):

print(index, ':', student_name)

print('')

print('')

print('Discussion Forum Unit 7')

Interpreter Output
= RESTART: D:\Users\Crystal Noralez\Documents\sync\UoPeople\Term 3\Programming Fundamentals\Unit
7\Assessment\Discussion Forum Unit 7.py

===================Example 1, Dictionary==================

Darlyn has 100 marks out of a possible 100.

Angel has 80 marks out of a possible 100.


Tiffany has 65 marks out of a possible 100.

Memory has 75 marks out of a possible 100.

===============Example 2, Zip function================

Darlyn has 100 marks out of a possible 100.

Angel has 80 marks out of a possible 100.


Tiffany has 65 marks out of a possible 100.

Memory has 75 marks out of a possible 100.

===================Example 3, Enumerate===================

0 : Darlyn

1 : Angel

2 : Tiffany

3 : Memory

>>> Discussion Forum Unit 7

Reference

Downey, A. (2015). Think Python| How to Think Like a Computer Scientist: Vol. Version 2.2.23 (2nd Edition). Green Tea Press.
https://my.uopeople.edu/pluginfile.php/1404469/mod_page/content/3/TEXT%20-%20Think%20Python%202e.pdf

Nguyen, D. (2021). The Immutable Tuple. Computational Methods in the Civic Sphere at Stanford University.
http://www.compciv.org/guides/python/fundamentals/tuples-immutable/
316 words

Permalink Show parent

Re: Discussion Unit 7


by Juan Duran Solorzano - Tuesday, 28 December 2021, 10:37 PM

Dear Crystal,

Well explained with examples easy to follow, what do you think are the pros and cons from the tuples?


Kind regards

Juan Carlos

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 17/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

25 words

Permalink Show parent

Re: Discussion Unit 7


by Crystal Noralez - Wednesday, 29 December 2021, 10:43 AM

It's an excellent question.

Tuples have the advantage of requiring less memory. Lists necessitate the use of extra memory.

The disadvantage is that tuples cannot be modified because they are immutable.

The advantage is that tuples can be used as a key in a dictionary. A list, on the other hand, does not allow you to do
so.

As a programmer, you should pick them.


65 words

Permalink Show parent

Re: Discussion Unit 7


by Yahya Al Hussain - Wednesday, 29 December 2021, 3:43 AM

Great attempt, great examples, the real world functionality is useful and helps explain the uses of each type.
18 words

Permalink Show parent

Re: Discussion Unit 7


by Yahya Al Hussain - Tuesday, 28 December 2021, 2:08 PM

Describe how tuples can be useful with loops over lists and dictionaries, and give Python code examples. Create your own
code examples. Do not copy them from the textbook or any other source. 

Your descriptions and examples should include the following: the zip function, the enumerate function, and the items method. 

to accurately describe the differences between them i will create some examples.

lists = ['cat', 'dog', 'horse',1, 2, 3.5]                                              #can be  changed

dictionaries = { 1: 'cat', 2: 'dog', 3: 'horse', 4: 1, 5: 2, 6: 3.5 }  #dictionaries are indexed by keys

tuples = ('cat', 'dog', 'horse',1, 2, 3.5)                                           #is indexed and can't be changed

lists.append(0)                                                           #adds a 0

dictionaries.append(0)                                              # returns error


tuples.append(0)                                                            # returns error

for i, ele in enumerate(lists):

   print(i, ele)
                                                          # returns

0 cat

1 dog


2 horse
3 1

4 2

5 3.5
https://my.uopeople.edu/mod/forum/discuss.php?d=640905 18/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

for i, ele in enumerate(dictionaries):

   print(i, ele)

                                                          # returns

0 1

1 2

2 3

3 4

4 5

56

for i, ele in enumerate(tuples):

   print(i, ele)
                                                          # returns

0 cat

1 dog

2 horse
3 1

4 2

5 3.5

list1 = ['first', 'second', 'third']

list2= [1, 2, 3]
#we can combine these 2 lists with zip into a list of tuples then use the enumerate function to iterate a sequence of pairs
for c, i in zip(list1, list2):

   print(c, i)
                                                          # returns

first 1

second 2

third 3

#in a dictionary we can use the  item method to create a similar result

d1 = {'first' : 1,'second' : 2,'third' : 3}

for (c , i) in d1.items():

     print(c, i)

                                                          # returns


first 1

second 2

third 3

283 words

Permalink Show parent


Re: Discussion Unit 7


by Juan Duran Solorzano - Tuesday, 28 December 2021, 10:53 PM

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 19/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

Dear Yahya,

Great examples, it shows you have a full understanding of the topic learned this week, a short description of why or when
should we use Tuples would have been very interesting to add up to your post.

Kind regards

Juan Carlos
43 words

Permalink Show parent

Re: Discussion Unit 7


by Yahya Al Hussain - Wednesday, 29 December 2021, 3:36 AM

thank you for your feedback, i will try better in the coming posts
13 words

Permalink Show parent

Re: Discussion Unit 7


by Crystal Noralez - Wednesday, 29 December 2021, 10:54 AM

Yahya,

Well great explain and good examples


7 words

Permalink Show parent

Re: Discussion Unit 7


by Simon Njoroge - Wednesday, 29 December 2021, 2:27 PM

Thanks for your input in this discussion. Your input is of much value and importance. Thanks for the good job.
20 words

Permalink Show parent

Re: Discussion Unit 7


by Juan Duran Solorzano - Tuesday, 28 December 2021, 10:00 PM

Tuples have very unique attributes in which tuples can be more concise and accurate than dictionaries and lists in certain
situations. 

What is a tuple? 

Tuples are immutables not like lists and dictionaries.  

Is a collection of elements separated by commas that are ordered and unchangeable. To create are different ways, the most
common way is using zip build-in function allowing us to use tuples to combine lists, strings, tuples, or dictionaries
maintaining the index of each sequence. 

letter = ["ABCD"]

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 20/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

numbers = [1,2,3,4]

zipped =zip(letter, numbers)

for i in zipped:

     print(i)

Output:

('A', 1)

('B', 2)

('C', 3)

('D', 4)

The zip function can take 2 or more sequences and return a list of tuples where each tuple contains one element from each
sequence. (Downey, 2016) 

Enumerate function can help us to convert a sequence into a sequence of tuples adding the index as its first value and the
sequence as its second value. This can be very useful when we have to know the index assigned to the values of the list. This
function can be used like this example:

groceries = ‘milk’, ‘grapes’, ‘pasta’, ‘chocolate’, ‘soda’ # tuple

for i, item in enumerate(groceries): # enumerate() returns a tuple of index and value

print(i, item)  # print index and value

Output:

0 milk

1 grapes

2 pasta

3 chocolate

4 soda

Items function help us to print all the keys and values from a dictionary, in which can be very useful when we want to change
or modify a value or a key.  

shop = {

"wallmart": "Sprite", 
"target": "Coke",

"Sams": 'Fanta',

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 21/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

"Oxxo": "Pepsi",

} # dictionary

items = shop.items() # items() method

print(items) # print tuple of tuples (key, value)

Once mentioned these examples the reasons we may choose to use tuples over dictionaries and lists are, firstly as I mentioned
at the beginning tuples are immutable which makes them less prompt to errors when we used them as arguments in functions.
Tuples can be converted to lists but it can require more time and compute power. If there is no need to change values or edit
keys we should consider keeping the data as a tuple where will not change along with the program.

References

Downey, A. B. (2016). Think Python: How to think like a computer scientist (2nd ed.). O’Reilly Media.

386 words

Permalink Show parent

Re: Discussion Unit 7


by Yahya Al Hussain - Wednesday, 29 December 2021, 3:37 AM

Detailed and excellent explanation, it is easy to read and i appreciate the real world examples .
17 words

Permalink Show parent

Re: Discussion Unit 7


by Crystal Noralez - Wednesday, 29 December 2021, 10:55 AM

Your work was straight to the point and in detail. Well done. Keep up the good job.
17 words

Permalink Show parent

Re: Discussion Unit 7


by Stephen Chuks - Wednesday, 29 December 2021, 1:18 PM

Nice explanation and good code examples. 

6 words

Permalink Show parent

Re: Discussion Unit 7 


by Janelle Bianca Cadawas Marcos - Wednesday, 29 December 2021, 11:56 AM

Using loops with tuples can make tuples more useful over lists and dictionaries. It can make the code simpler and cleaner.

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 22/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

Example using zip():

This shows that tuples with loops are more useful than just lists because it was able to print out the names and how many
pets they have really easily with a simple loop. It was made cleaner with the tuple return value of the zip() function.

input:

names = ['Anna','Benjamin','Carlos']

pets = [3,4,1]

#no tuple

for x in range(len(names)):

     print(names[x],pets[x])

#zipping lists together to return tuple value

Z = list(zip(names,pets))

for a,b in Z: #loop with tuple

     print(a,b)

output:

Anna 3

Benjamin 4

Carlos 1

Anna 3

Benjamin 4

Carlos 1

Example using enumerate():

This example shows an inventory list and I want to print out their indices and their item. It was made a lot simpler with the
tuple return value of the enumerate() function.

input:

inventory_list = ['dog food','treats','collars','bowls','leashes']

#no tuple

num = 0 #index value

for item in inventory_list:

     print(num,item) #print index and item

     num += 1 #add +1 index value

#using tuple return value of enumerate()

for a,b in enumerate(inventory_list): #loop with tuple

     print(a,b)

output:

0 dog food

1 treats

2 collars

3 bowls

4 leashes

0 dog food

1 treats

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 23/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

2 collars

3 bowls

4 leashes

Example using item():

This shows that using a tuple to return each value of the dictionary is really easy with the function items(). I’m not even sure
how to print it out without the item() function since I’m still learning.

input:

d = {'Game':'Borderlands 3','Class':'Siren','Name':'Amara'}

#can print each dictionary key and value out simply with tuple return items()

for a,b in d.items():

     print('The',a,'is', b)

output:

The Game is Borderlands 3

The Class is Siren

The Name is Amara


293 words

Permalink Show parent

Re: Discussion Unit 7


by Luke Henderson - Wednesday, 29 December 2021, 11:43 PM

Great explanations of each of the functions. You provided your code and also the output. great job. I particularly like your
use of the items() function and the output which could be useful in many situations
36 words

Permalink Show parent

Re: Discussion Unit 7


by Stephen Chuks - Wednesday, 29 December 2021, 12:41 PM

Tuples can be useful with loops over dictionaries when we want to iterate over dictionary elements. The use of .items() method
returns a list containing the key-value as tuple pairs of the dictionary.

tuples can be useful with loops over lists when we want to iterate two lists in one loop. In this case, we use the zip() functions.

We can also use the enumerate()method to return an object of the enumerate class for any given object that supports
iteration. This method prints out the iteration values and the index.

The zip function

names=['mike', 'Stephen', 'James']

age= [25,23,22]

zipped=zip(names,age)

list(zipped)

dict.items() method

students={'Mike':25, 'Stephen':23, 'James':22}

print(students.items())

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 24/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

enumerate method

my_lists = ['Goat','Whale','London', 'New York']

enum_list = enumerate(my_lists)

print(type(enum_list))

enumlist = list(enum_list)

print(enumlist)
121 words

Permalink Show parent

Re: Discussion Unit 7


by Luke Henderson - Wednesday, 29 December 2021, 11:40 PM

Short and to the point post. You covered the necessary criteria, and demonstrate your understanding of the functions and
their uses. However it would have been good for you to post the output of your code.
36 words

Permalink Show parent

Re: Discussion Unit 7


by Peter Odetola - Wednesday, 29 December 2021, 9:23 PM

CS1101 DISCUSSION FORUM UNIT 7

Describe how tuples can be useful with loops over lists and dictionaries, and give Python code examples. Create your own
code examples. Do not copy them from the textbook or any other source.

Your descriptions and examples should include the following: the zip function, the enumerate function, and the items method.

ANSWERS

A tuple is an ordered set of data that cannot be changed. Therefore, tuples are immutable lists and their immutability property
is what makes them useful in iterating over lists and dictionaries. Tuples can store attributes in a single object without creating
parallel lists. Tuples are faster than lists and dictionaries as they are immutable.

A list is an ordered set of data that can be changed. Therefore, lists are mutable and they allow duplicate members. Lists
require overhead

A dictionary is a collection that is unordered, changeable, and indexed. Dictionaries have keys and values instead of positions
such as 0,1,2 etc.

Tuples can be used either as keys or values in a dictionary whereas lists and dictionaries can only be used as values in a
dictionary.

There some built-in functions or methods in both the tuple and dictionary data structures that are designed to iterate over lists
or dictionaries. A few of such are;

The dict.item() Method

The dict.items() method returns a list of tuple pairs (Keys, Values) in the dictionary. The following is a sample code to illustrate
the use of items() method which iterates through a dictionary and returns a key-value pair as a list each time;

Code:

==============================

# the dictionary below contains children's names and their ages.

children_age = {'Mercy':3, 'Emmanuel':6, 'Hephzibah': 10, 'Amarachi' 15, 'Peter':20}

print("Children age: %s" % list(children_age.items()))

Output:

==============================

Children ages: [('Mercy', 3), ('Emmanuel', 6), ('Hephzibah', 10), ('Amarachi', 15), ('Peter', 20)]

THE ZIP() FUNCTION

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 25/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

The zip() function takes two or more iterable objects as arguments and returns an iterator of tuples. By the way, an iterator is
an object that contains a countable number of values. The number of arguments supplied in a zip function determines the
number of items in the tuples created. And where the items in the objects supplied as arguments are not equal,

Code:

==============================

#list of children's names

children_name = ("Mercy", "Emmanuel", "Hephzibah", "Amarachi", "Peter")

#list of the children’s position by birth

birth_position = ["5th", "4th", "3rd", "2nd", "1st"]

print(type(birth_position))

#list of children academic level

academic_level = ["Preschool", "Primary", High-School", "College", "University"]

#using zip() function

children_info = list(zip(children_name, birth_position, academic_level))


print(children_info)

Output:

==============================

[("Mercy", "5th", Preschool), ("Emmanuel", "4th", Primary), ("Hephzibah", "3rd", High-School), ("Amarachi", "2nd", "College"),
("Peter", "1st", "University")]

THE ENUMERATE() FUNCTION

The enumerate() function with a for loop takes an iterable sequence (e.g. strings, lists, tuples etc.) and returns a sequence of
tuples containing index and their corresponding elements.

Code:

std_name = ("Mercy", "Emmanuel", "Hephzibah", "Amarachi", "Peter"

for index in enumerate(children_name):

print(index)

Output:

==============================

(0, ("Mercy")

(1, "Emmanuel")

(2, "Hephzibah")

(3, "Amarachi")

(4, "Peter")

References

Downey, A. (2015). Think Python, How to think like a computer scientist. This book is licensed under Creative Commons
AttributionNoncommercial 3.0 Unported (CC BY-NC 3.0)
511 words

Permalink Show parent

Re: Discussion Unit 7


by Luke Henderson - Wednesday, 29 December 2021, 11:38 PM

Great examples for zip(), enumerate() and dict items method. You displayed that you understood the terms and their use.
19 words

Permalink Show parent


Re: Discussion Unit 7
by Luke Henderson - Wednesday, 29 December 2021, 11:31 PM

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 26/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

Tuples are a data type in python which look a little like lists. However, they are immutable. Using tuples to iterate over lists and
dictionaries is less error prone due to the fact that elements cannot be accidentally changed as they could with lists.

Combining a list with a dictionary it is possible to iterate through a list and create keys in a dictionary and assign values to
each key from the list like so:

d = dict()

animals = [“cat”, “dog”, “fish”, “bird”, “mouse”, “frog”]

for i in animals:

d[i] = 1

Ouput:

print(d)

{'cat': 1, 'dog': 1, 'fish': 1, 'bird': 1, 'mouse': 1, 'frog': 1}

dictionary.items()

This handy function provided with the dict data type will return the key/value pairs of a dictionary in a set of tuples

myFamily = {“Mum” : 56, “Dad” : 55, “Brother” : 33, “Sister” : 27}

myFamily.items()

dict_items([('Mum', 56), ('Dad', 55), ('Brother', 33), ('Sister', 27)])

zip() function

zip is a function which iterates through a set of tuples or lists and joins them into a bunch of tuple pairs

zip can be used to efficiently create key/value pairs from a set of lists

animals = [“cat”, “dog”, “fish”, “bird”, “mouse”, “frog”]

numbers = [0,1,2,3,4,5]

d = dict(zip(animals,numbers))

Output:

print(k)

{'cat': 0, 'dog': 1, 'fish': 2, 'bird': 3, 'mouse': 4, 'frog': 5}

enumerate() function

The enumerate function iterates through a list and numbers each item in the list. This can be useful for assigning numbered
keys to each element of a list and saving the elements as dictionary values.

Animals = dict(enumerate(animals))

print(Animals)

{0: 'cat', 1: 'dog', 2: 'fish', 3: 'bird', 4: 'mouse', 5: 'frog'}

References

Downey, A. (2015). Think Python, How to think like a computer scientist. This book is licensed under Creative Commons
Attribution-Noncommercial 3.0 Unported (CC BY-NC 3.0)
298 words 
Permalink Show parent

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 27/28
1/5/22, 1:50 AM CS 1101 - AY2022-T2: Discussion Unit 7

UoPeople Clock (GMT-5)

All activities close on Wednesdays at 11:55 PM, except for Learning Journals/Portfolios which close on Thursdays at 11:55 PM always
following the clock at the top of the page.

Due dates/times displayed in activities will vary with your chosen time zone, however you are still bound to the 11:55 PM GMT-5
deadline.

◄ Learning Guide Unit 7

Jump to...

Programming Assign. Unit 7 ►

Disclaimer Regarding Use of Course Material  - Terms of Use


University of the People is a 501(c)(3) not for profit organization. Contributions are tax deductible to the extent permitted by law.
Copyright © University of the People 2021. All rights reserved.

You are logged in as Stephen Chuks (Log out)


Reset user tour on this page
 www.uopeople.edu










Resources
UoPeople Library
Orientation Videos
LRC
Syllabus Repository
Honors Lists
Links
About Us
Policies
University Catalog
Support
Student Portal
Faculty
Faculty Portal
CTEL Learning Community
Office 365
Tipalti
Contact us
English (‎en)‎
English (‎en)‎
‫ العربية‬‎(ar)‎

Data retention summary



Get the mobile app

https://my.uopeople.edu/mod/forum/discuss.php?d=640905 28/28

You might also like