You are on page 1of 32

Nabeel Fahim

Home

Home  My courses  CS 1101 - AY2020-T5  30 July - 5 August  Discussion Forum Unit 7  DISCUSSION
ASSIGNMENT: UNIT 7

Search forums

Discussion Forum Unit 7


DISCUSSION ASSIGNMENT: UNIT 7
Settings Subscribe

  

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

DISCUSSION ASSIGNMENT: UNIT 7


by Isaac Ayetuoma (Instructor) - Wednesday, 17 June 2020, 5:11 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 ASSIGNMENT: UNIT 7


by Elad Tenenbom - Thursday, 30 July 2020, 10:33 AM

Tuple is basically an object that contains a sequence of objects. Similar to lists. 


Using tuples in loops allows us to iterate over more than one values at the same time.  /
I personally don't like it, I think it does save some code, but it is a little bit confusing and I prefer
my loops more traditional.

Example attached below.


60 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Troycie Celestine - Friday, 31 July 2020, 8:54 AM

Great job posting rst. It looks like you have provided a great example for a tuple.
However, it appears you are missing the other required examples for the zip function, the
enumerate function, and the items method.
37 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Gbolahan Gadegbeku - Saturday, 1 August 2020, 9:44 PM

Elad good job with the way you di erentiated the Tuples in relating to lists and
dictionary. However, I am a little confused with your example of using the zip and
enumerate functions. Please do clarify on that.
37 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Isaac Ayetuoma (Instructor) - Saturday, 1 August 2020, 11:40 PM

Dear Elad,
That was a good attempt, but more details and examples would have increased the quality
of your response. Consider Troycie's feedback.

Success wishes and stay safe, 


Isaac Ayetuoma /
30 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Enrique Gomez - Monday, 3 August 2020, 12:40 AM

Hi Elad. In this case you provides a good example for   tuples and dictionaries 

The Output for your code:

the Gorila lives in cage number 1

the Lion lives in cage number 2

the Tiger lives in cage number 3

All the requirements for this Assignment are interesting to test it. The use of zip object, the
built-in function enumerate and item method are clear examples to work tuples with lists
and dictionaries. It is said Dictionaries are one of Python´s best features, they are the
building blocks of many e cient and elegant algorithms (Downey, A. 2015), so it´s a great
challenge for  all of us to explore and implement them in our forthcoming projects.

                                                                             REFERENCES

Downey, A. (2015). Think Python: How to think like a computer scientist. Needham,
Massachusetts: Green Tree Press. 

134 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Vernon Tembo - Monday, 3 August 2020, 1:51 AM

Hello Elad Tenenbom


its unfornuate that you have given only one examples, which is very helpful by the way.
Would have loved to see more from you because your explanations are excellent and
simple.
Good job
36 words 
Permalink Show parent /
Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Jonathan De Beer - Tuesday, 4 August 2020, 3:11 AM

Hey Elad, your example is easy to understand, and you describe it perfectly. Would love to
see you elaborate further, as it is easy to learn from you. Well done and good luck in the
future.
36 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Alessandro Galassi - Tuesday, 4 August 2020, 4:04 AM

Hi, Elad. This was a good example of a tuple, although I believe you were supposed to
elaborate with more examples, using a zip, enumerate and items method.
28 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Jonathan De Beer - Friday, 31 July 2020, 5:11 AM

#The enumerate() function is used


#to iterate through a list.
pets = ('Pigeon', 'Gorilla', 'Morpheus', 'Eagle')
for i, pet in enumerate(pets):
print (i, pet)
#output is
#0 Pigeon
#1 Gorilla
#2 Morpheus
#3 Eagle

#the zip operator joins two tuples together


numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
zipped = zip(numbers, letters)
list(zipped)
#output
#[(1, 'a'), (2, 'b'), (3, 'c')]

Dictionary1 = { 'A': 'Boys', 'B': 4, 'C': 'Girls' } 


/
print("Original Dictionary items:")

items = Dictionary1.items()

print(items)

#output
#Original Dictionary items:
#dict_items([('A', 'Boys'), ('B', 4), ('C', 'Girls')])
90 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Troycie Celestine - Friday, 31 July 2020, 8:59 AM

Great job here. It looks like you hit all the required examples spot on. However, I
attempted to run the inputs you provided to see if they matched. It seems there may be an
issue with the zip example as it does not provide an output.
46 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Gbolahan Gadegbeku - Saturday, 1 August 2020, 9:54 PM

Good job with your examples Jonathan. But, I observed like Troycie mentioned that
your code for the zip function did not run.
22 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Jonathan De Beer - Sunday, 2 August 2020, 4:09 AM

hey thanks for pointing that out ill see why


9 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Jonathan De Beer - Sunday, 2 August 2020, 4:11 AM

do you have any idea why the zip function isnt working ?
11 words

/
Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Jonathan De Beer - Sunday, 2 August 2020, 4:11 AM

do you have any idea why the zip function isnt working ?
11 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Troycie Celestine - Sunday, 2 August 2020, 9:25 AM

I think it should be ore like this, I just changed numbers and letters to n and l to
make it easier for me,

#the zip operator joins two tuples together


n = [1, 2, 3]
l = ['a', 'b', 'c']
zipped = list(zip(n, l))
print('zip example = ',zipped)
for n,l in zipped: #loop over lists
print(n,l)
59 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Jonathan De Beer - Tuesday, 4 August 2020, 3:21 AM

Thank you Troycie


3 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Isaac Ayetuoma (Instructor) - Tuesday, 4 August 2020, 6:57 PM

Thank you Troycie for making it clearer for Jonathan.


Regards,
Isaac Ayetuoma
12 words

Permalink Show parent



/
Re: DISCUSSION ASSIGNMENT: UNIT 7
by Enrique Gomez - Monday, 3 August 2020, 12:51 AM

Hi, With Jupyter there is no problem with the zip example.

OUTPUT
[(1, 'a'), (2, 'b'), (3, 'c')]

But in IDLE, it is necessary to add print to list(zipped)

print(list(zipped)), in this way it displays:

[(1, 'a'), (2, 'b'), (3, 'c')]


44 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Enrique Gomez - Monday, 3 August 2020, 1:20 AM

Hi Jonathan, It is clear for you the use of the zip function, the enumerate function, and the
items method. The examples for zip operator and Dictionary are really good, but it is
necessary to describe how items method works with loops over dictionaries and how zip is
used with loops.  

Dictionaries: According to Downey, A. (2015)


>>> d = {'a':0, 'b':1, 'c':2}
>>> for key, value in d.items():
... print(key, value)
...
c2
a0
b1

The most common use of zip is in a for loop . According to Downey, A. (2015):
>>> s = 'abc'
>>> t = [0, 1, 2]

>>> for pair in zip(s, t):


... print(pair)
...
('a', 0)

/
('b' 1)
('b', 1)
('c', 2)

                                                                                                                       REFERENCES
Downey, A. (2015). Think Python: How to think like a computer scientist. Needham,
Massachusetts: Green Tree Press.

132 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Jonathan De Beer - Tuesday, 4 August 2020, 3:21 AM

Thanks Enrique
2 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Isaac Ayetuoma (Instructor) - Tuesday, 4 August 2020, 6:59 PM

Thank you Enrique for the details given and for clarifying using the Jupyter and IDLE.

Regards,
Isaac Ayetuoma
18 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Alessandro Galassi - Tuesday, 4 August 2020, 4:06 AM

well done, Jonathan. from what I understand, it looks like these are all apt examples. I had
some trouble understanding and executing this assignment but these are pretty clear and
understandable examples. I think I would have been better o seeing this before i
attempted the assignment, lol.
48 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7 


by Jonathan De Beer - Tuesday, 4 August 2020, 8:38 AM
/
thanks man
2 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Isaac Ayetuoma (Instructor) - Tuesday, 4 August 2020, 7:01 PM

Hello Jonathan,
By posting early, you were able to receive adequate reviews from peers and
understanding is therefore enhanced. Well done!

Regards,
Isaac Ayetuoma
24 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Jonathan De Beer - Wednesday, 5 August 2020, 4:47 AM

Thank you sir


3 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Troycie Celestine - Friday, 31 July 2020, 8:47 AM

Inputs
#Tuples can be more useful over lists and dictionaries with loops as they're faster . It is because
tuples are immutable i.e. it is stored in single block of memory and there is no need of extra
space to store new objects .

#Time Di erences

import timeit
c1='''
a=(1,2,3)'''
c2='''
a=[1,2,3]'''
c3='''
l={1:-1,2:-2,3:-3}'''
print("tuple")

/
print(timeit.timeit(c1,number=1000000))
print("List")
print(timeit.timeit(c2,number=1000000))
print("Dictionary")
print(timeit.timeit(c3,number=1000000))

#While reading through two lists, zip functions returns a collection of tuples (a , b) where a is ith
element of List 1 and b is ith element of List 2

List1=[1,2,3,4,5,6,7,8,9,10]
List2=[-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]
Z=zip(List1,List2)
print(list(Z))
'''
for a,b in Z:
print(a,b)
'''

List1=[1,2,3,4,5,6,7,8,9,10]
List2=[-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]
Z=zip(List1,List2)
for a,b in Z:
print(a,b)

#Enumerate function adds a counter to the list or tuple . It returns an object which when
converted into list can be clearly seen as list of tuples of (counter , element)

List1=[1,2,3,4,5,6,7,8,9,10]
List2=[-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]
print(list(enumerate(List1)))

#items method returns an object which can be clearly seen as tuples having (key, value)
l={1:-1,2:-2,3:-3,4:-4}
print(l.items())


/
Outputs

237 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Jonathan De Beer - Tuesday, 4 August 2020, 3:14 AM

Good work Troycie, you have taught me some new things about the items method that I
didn't know. Well done.
20 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Alessandro Galassi - Tuesday, 4 August 2020, 4:10 AM

this is spot on! I had di culties understanding this topic, although your submission made
things clear. Thanks!
17 words

Permalink Show parent /
Re: DISCUSSION ASSIGNMENT: UNIT 7
by Abdulaziz Idris Abubakar - Wednesday, 5 August 2020, 11:36 AM

Hi Troycie,
Your post is signi cant and you have broaden the discussion. I also learned new pattern
from your work
20 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Enrique Gomez - Saturday, 1 August 2020, 6:09 PM

LISTS AND TUPLES

Tuples are useful with loops over lists when the built-in function zip is used. Zip is a function
that takes two or more sequences and returns a list of tuples where each tuple contains one
element from each sequence. The most common use of  zip is in a   “for loop”. In this case we
have an element of each list s and t. the zip object is an iterator (Downey, A. 2015)

 s= ["Age", "Gender", "ID"]

t=[35, "Male", "96857452"]

for pair in zip(s, t):

print(pair)

OUTPUT

('Age', 35)

('Gender', 'Male')

('ID', '96857452')

If you have a list of tuples, elements of the sequence and their indices can be traversed by using
the built-in function enumerate. The result from enumerate is an enumerate object, which
iterates a sequence of pairs; each pair contains an index (starting from 0) and an element from
the given sequence (Downey, A. 2015):

 s= ["Father´s Name ", "Mother´s Name"]

t=["George", "Elizabeth"]

A list of tuples can be obtained by using zip object, in this case:



list(zip(s,t)) /
OUTPUT

[('Father´s Name: ', 'George'), ('Mother´s Name:', 'Elizabeth')]

Then using built-in function enumerate

t=list(zip(s,t))

for index, element in enumerate(t):

    print(index, element)

OUTPUT

0 ('Father´s Name: ', 'George')

1 ('Mother´s Name:', 'Elizabeth')

DICTIONARIES AND TUPLES

Tuples are useful with loops over Dictionaries with  a method called items that returns a
sequence of tuples, where each tuple is a key-value pair.(Downey, A. 2015)

d = {'8:00am': "Programming Fundamentals" , '10:00am': "English Composition 1", '1:00pm':


"Online Education Strategies"}

t = d.items()

for key, value in t:

    print(key, value)

OUTPUT

8:00am Programming Fundamentals

10:00am English Composition 1

1:00pm Online Education Strategies

                                                                                                 REFERENCES

 Downey, A. (2015). Think Python: How to think like a computer scientist. Needham,
Massachusetts: Green Tree Press. 

/
308 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Gbolahan Gadegbeku - Saturday, 1 August 2020, 9:56 PM

Great Job Enrique. I love all the examples you use above,
11 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Vernon Tembo - Monday, 3 August 2020, 1:29 AM

Hello Enrique Gomez


Your examples are simple and easy to understand. Once again your post has answered all
the questions as required.
Good job
24 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Krista White - Monday, 3 August 2020, 12:42 PM

Hi Enrique,

Great job. Your explanations and examples provide enough detail to help the reader
understand without being overly di cult or cumbersome. I liked your two di erent ways
of displaying your zipped list: "for pair in zip(s, t): print(pair)" (which prints each pair on a
separate line) and "list(zip(s,t))" (which just prints the results as a new list). It's interesting
to see the multiple ways one could do that. I will admit, I came to your post because I was
hoping it would shed some light on a question I had, however since that was in no way
part of the assignment I can't blame you for not doing so. The question was this: what
exactly is the point of the items method for a dictionary? Ok, so it organizes the key-value
pairs into tuples, so what? Why is that helpful? That's not necessary for iterating through
the items in a dictionary, so what does it allow you to do? Anyway, I don't know if you know
the answer, and it's ne if you don't, but I hoped maybe you might :). The only reason I can
think of is that maybe using tuple assignment on the items in a dictionary would be
useful.... somehow?
209 words

Permalink Show parent



/
Re: DISCUSSION ASSIGNMENT: UNIT 7
by Jonathan De Beer - Tuesday, 4 August 2020, 3:15 AM

Thanks for this clear post Enrique, I really enjoyed your format. Really well done and good
luck in the future.
20 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Abdulaziz Idris Abubakar - Wednesday, 5 August 2020, 11:29 AM

Hi Enrique,

Your work is uniquely done and your examples are understandable, Also the format of
your presentation is superb and you answered all the questions as required!
28 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Nabeel Fahim - Wednesday, 5 August 2020, 11:47 PM

Hi Enrique!

Thank you! I had tough time just understanding the context of the assignment. That is why
I was very nervous whether I was even submitting required work or not. Your explanation
rea rmed me. It is always great to see you put understandable work for your peers.
48 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Gbolahan Gadegbeku - Saturday, 1 August 2020, 9:32 PM

Tuples are more e ective over lists and dictionaries with loops because they are faster and
immutable.
My example:
Input:
data = [('mercedes', 10), ('ferrari', 7), ('lamborghini', 8)]
# to print each car's race time info:
for (car, mph) in data:
print(car, 'has', mph, 'mph') 
Output: /
============= RESTART: C:/Users/Oamos/Downloads/script for part2.py ============
mercedes has 10 mph
ferrari has 7 mph
lamborghini has 8 mph
>>> Description of my example using the zip and enumerate functions:
#using the zip function which help to zip 2 lists together.
Assuming the above data was in 2 parallel lists:
# the zip function is used to zip 2 lists together.
Suppose the above data was in 2 parallel lists:
Input:
car = ['mercedes', 'ferrari', 'lamborghini']
mph = [10, 7, 8]

# then we can print same output using below syntax:


for (car, mph) in zip(car, mph):
print(car, 'has', mph, 'mph')
Output:
============= RESTART: C:/Users/Oamos/Downloads/script for part2.py ============
mercedes has 10 mph
ferrari has 7 mph
lamborghini has 8 mph

# The enumerate function assigns the indices to individual elements of list.


#If index is assigned to each racer, that can be represented below:
for (index, car) in enumerate(cars):
print(index, ‘:’,car)

# The items method is used in dictionary, where it returns the key value pair of
# the dictionary in tuple format
# if the above tuple list was in dictionary format like below:
Input:
carDict = {'mercedes': 10, 'ferrari': 7, 'lamborghini': 8}

# Then using the dictionary, we can print same output with below code:
for (car, mph) in carDict.items():
print(car, 'has', mph, 'mph')
Output:
============= RESTART: C:/Users/Oamos/Downloads/script for part2.py ============
mercedes has 10 mph
ferrari has 7 mph
lamborghini has 8 mph
>>>
282 words

/
Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Vernon Tembo - Monday, 3 August 2020, 1:43 AM

Dear Gbolahan Gadegbeku


I must say i was a little confused with your work so much so that I had to run your codes
just to be sure and they turned out ne. Like in the rst example, I thought mph was not
de ned so there was no way the code will work now i see it referred to the second
elements in each tuple of the list. Its indeed true there are many di erent ways of doing a
task and you still get the same output.
excellent work
89 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Ndumiso Mkhize - Tuesday, 4 August 2020, 12:19 PM

Hi Gbolahan

Good work, you example was well de ned for each category but i would ask if you could
make the code a bit more formatted, with the indents especially for your loops so that it is
easier to read. It helps us a lot as we learn your example with much better understanding.

Good job all in all.


59 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Vernon Tembo - Sunday, 2 August 2020, 6:07 PM

A function can only return one value but if a value is a tuple, it can return multiple values. A
tuple can be used to store the results or store elements separately, (Downey, 2015). Tuples are
more useful for loops because they can return two or more values. They allow functions to
e ciently compute more than one statement at the same time. It is this ability that makes it
useful in loops.
Example 1
Implementing a zip function returns two values by extracting an element from the rst
sequence and mapping it unto another element from the second sequence.
Python code
>>> tittle='Father', 'Mother', 'Son', 'Daughter'
>>> age=[49, 38, 20, 13]

/
>>> i (tittl )
>>> zip(tittle, age)

>>> #Now using the zip function in a loop

>>> def member_age():


                 for v in zip(tittle, age):
                           print(v)
Output
>>> member_age()
('Father', 49)
('Mother', 38)
('Son', 20)
('Daughter', 13)

Example 2
“An enumerate function iterates a sequence of pairs; each pair contains an index (starting from
0) and an element from the given sequence,” (Downey, 2015. p. 119). The index corresponds
directly to the element and indicates the element’s position in a sequence.
Python Code
>>> v='FAMILY'
>>> def index2element():
                     for index, element in enumerate(v):
                               print(index, element)
Output
>>> index2element()
0F
1A
2M
3I
4L
5Y
Example 3
“Dictionaries have a method called items that returns a sequence of tuples, where each is a key-
value pair,” (Downey, 2015. p. 120). Again to be able to have an output that has more than one
value, a return value must be in form of tuple.
Python code
>>> tittle2age=dict()
>>> tittle2age={'Father':49, 'Mother':38, 'Son':20, 'Daughter':13}
>>> verbo=tittle2age.items()
>>> verbo
dict_items([('Father', 49), ('Mother', 38), ('Son', 20), ('Daughter', 13)])
>>> #using it in a loop
>>> def member2age():
                   for key, value in verbo:

/
i t(k l )
                            print(key, value)
Output
>>> member2age()

Father 49
Mother 38
Son 20
Daughter 13

REFERENCE

Downey, A. (2015). Think Python: How to think like a computer scientist. Needham,


Massachusetts: Green Tree Press. 

332 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Abdulaziz Idris Abubakar - Wednesday, 5 August 2020, 11:31 AM

Hi Vernon,
After going through your post I can say you make a signi cant contribution and Your codes
are easy to understand.
22 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Ndumiso Mkhize - Monday, 3 August 2020, 7:32 AM

One of the major advantage of tuples over both lists and dictionaries is that tuples are
immutable, they cannot be changed, with list and dictionaries being mutable, meaning that
even after you have de ned you list it is possible to update the individual elements/items in the
list and therefor using a tuple over a list lets the interpreter know that the data parsed or used
should not be changed. 

Tuples are useful with loops when you iterate two lists together in one loop by using the
zip() function that returns the collection of tuples( ) as in my example, tuples (big, small).

'''Using two list with elements of animals big and small (adult and baby)'''

big =['dog', 'cat', 'bear'] # List 1 with adult animals.


small = ['puppy', 'kitten', 'cub'] # List 2 with baby animals.

zipped = list(zip(big, small)) # Using the zip function to join the 2


lists together.
print(zipped

for big, small in zipped: # Using for loop with the zipped tuple /
print(big, small)

Output:

[('dog', 'puppy'), ('cat', 'kitten'), ('bear', 'cub')]    #Tuples within a list, making it easier to read the
list  - advantage.

dog puppy

cat kitten

bear cub

While using loops, the enumerate() function returns a tuple containing a count for every
iteration, from the 1st indexed element, and the values obtained from iterating over a
sequence. 

fruits = ('banana', 'apples', 'oranges', 'pears') # Tuple assignment.


for index, fruits in enumerate(fruits): # Using the enumerate function to
index the tuple.
print(index, fruits)

Output:
0 banana

1 apples

2 oranges

3 pears

Tuples are useful with loops over dictionaries  when you want to iterate all dictionary
elements (keys and values), you use the .items() method which returns the collection of
tuples with the key pairs as  a key and a value (key, value) of the original key-pair of the
dictionary.

'''Using a dictionary that takes a pets name and its age and owners name'''

vet_file = {'pet_name': 'Bobby', 'pet_age':8 , 'owner': 'Mike' } # Dictionary


assignment

for key, value in vet_file.items(): #Looping from the dictionary using key, v
alue tuple
print(key, value) #For each loop through the key-pairs will be pr
inted.

Output:
pet_name Bobby

pet_age 8

owner Mike

/
Reference:
nd
Downey, A. (2015). Think Python, how to think like a computer scientist, 2  Edition.

364 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Krista White - Tuesday, 4 August 2020, 8:35 AM

Good job Ndumiso,

One small thing- it looks like you forgot a parenthesis at the end of the line "print(zipped"
from your rst example. Other than that, everything looks good. I'll ask you the same thing
I asked Enrique- what do you think is the bene t of using the items method on a
dictionary? It's certainly not wrong, but in your example, the output could have easily been
accomplished without that method by using key and key[val]. I don't know the answer to
that question, but I'm asking because I hope someone else does.
96 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Ndumiso Mkhize - Tuesday, 4 August 2020, 11:59 AM

Hi Krista

Thank you for your observation about the parenthesis, i think i must have not copied
it properly from PyCharm. With regards to your question i would take a guess that if
you want to get the full 'items' being the keys and their values as both being called in
their entity rather than to call the key alone, which yes granted if you call the key the
value associated will also be present since they are value pairs. I think its a much
clearer approach to the code, that the items are represented by both the key and
value.

Its a good question and i hope we can both get a more academic answer if someone
can elaborate for us.
122 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7 


by Elad Tenenbom - Wednesday, 5 August 2020, 3:07 AM
/
Well done Ndumiso, the introduction is very helpful and interesting.
10 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Nabeel Fahim - Wednesday, 5 August 2020, 11:49 PM

Hi Ndumiso,

Wow! you are very diligent and I must say i need to learn a lot from your learning attitude.
There is nothing much to say about your submission. It was neatly done. 

BR

35 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Abdulaziz Idris Abubakar - Monday, 3 August 2020, 7:57 AM

Discussion Forum Unit 7


CS 1101 - AY2020-T5
August 3, 2020

Tuples are like list but their value does not change. It is also possible to convert list into a tuple.
Tuples are useful over list and dictionary by using built in function .items() which returns the
collection of tuples e.g. key and value.
>>> b = {“name”: “Abdul”, “Age”:, “24” , “marital status”: “single”} #sample of dictionary.
>>> b
{‘name’: ‘Abdul’, ‘Age:, ‘24’ , ‘marital status’: ‘single’}
>>> l = list.(b.items()) # Using built in function list to the key and value which are tuples.
>>> print(“b.items() = “ , l)
b.items() = [(‘name’, ‘Abdul’), (‘age’, ‘24’), (‘marital status’, ‘single’)]
>>> for k, v in b.items():
. . . print(“The key is “, k, “, The value is “,v)
...
The key is name , The value is Abdul
The key is age , The value is 24
The key is marital status, The value is single
Tuple can also be use in iterating two lists in one loop by using built in function zip()
>>> x = [“ rst” , “second” , “third”] # rst list
>>> y = [1, 2, 3]#second list

/
>>> zipped = list(zip(x y))
>>> zipped list(zip(x, y))
>>> print(“zipped = “ ,zipped)
zipped = [(‘ rst’ , 1), (‘second’ , 2), (‘third’ , 3)]

>>> for x,y in zipped:


. . . print(a,b)
...
rst 1
second 2
third 3
202 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Elad Tenenbom - Wednesday, 5 August 2020, 3:11 AM

Abdulaziz, your solution is very simple and easy to understand, thanks.


11 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Khai Lamh Cin - Wednesday, 5 August 2020, 12:00 PM

Hi Abubakar,

That was a simple solution, but feel we missed enumerate function to add.
Thanks
16 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Krista White - Monday, 3 August 2020, 10:58 AM

Tuples can be particularly useful with loops over lists when used with the zip function. Using
tuple assignment, you can iterate through multiple lists with one pass, as seen below. You can
also use enumerate to give each item pair an index number, so that it they are easily
identi able (Downey, 2015). In this way, you could write a useful check of previously written
code, to ensure that code is doing what it's supposed to do.

INPUT

lyst = [1,4,8,5,17,23]

squares = [1,16,65,25,289,529]

/
 

def check_squares(lyst, squares):

    for index, (a, b) in enumerate(zip(lyst, squares)):

        if b != a**2:

            print('There is a problem at index number',index,'in the lists')

check_squares(lyst, squares)

OUTPUT

There is a problem at index number 2 in the lists

Tuples can also be used to iterate through dictionaries through the use of of the items method,
which groups each key-value pair into a tuple (Downey, 2015). In this way, the key-value pairs
are more easily searchable.

INPUT

npa = {'a':'Alpha', 'b':'Bravo', 'c':'Charlie', 'd':'Delta', 'e':'Foxtrot'}

def check_npa(d):

    for k, v in d.items():

        if k.upper() != v[0].upper():

            print('There is a problem at',k)

check_npa(npa)

OUTPUT

There is a problem at e

References:

1. Downey, A. (2015). Think Python, how to think like a computer scientist, 2nd Edition.

227 words 
/
Permalink Show parent
Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Khai Lamh Cin - Wednesday, 5 August 2020, 11:57 AM

Hi Krista,
That was a nice try, I feel like it was somehow confusing the program printing error
message. I have tried to nd why number '2' and 'e' got the problem but still could not nd
a solution myself. Thank you and hope I could have a change to see the point.
53 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Krista White - Wednesday, 5 August 2020, 1:45 PM

Hi Khai,

I purposely included an error in my input, so it could be shown in the output that the
program had correctly detected that. So my program worked as intended. Was that
your question?
35 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Alessandro Galassi - Tuesday, 4 August 2020, 3:55 AM

Description:

Tuples are immutable, which means they can't be changed - they are solidi ed for the entire
program, whereas lists and dictionaries can be modi ed. For this reason, Tuples can be less
problematic and more useful with loops.

#Zip Function example

>>> ev = [2,4,6]
>>> od = [3,6,9]
>>> my_tuple = list(zip(ev,od)) #zip function
>>> my_tuple
[(2, 3), (4, 6), (6, 9)] #listed tuples
>>> for x,y in my_tuple: #using for loop
print(x,y)
2 3 #output


4 6
6 9
>>> 
/
#Enumerate example

>>> racewinner_medals = ('gold','silver','bronze') #creating a tuple


>>> for place, medal in enumerate(racewinner_medals): #using enumerate functi
on
print(f'{place}: {medal}')

0: gold #output
1: silver
2: bronze

#Items method example

>>> dic = {'gloves':'boxing','shoes':'running'} #defining a dictionary


>>> for key,val in dic.items(): #using items method
print('{key},{val}'.format(key=key, val=val))

gloves,boxing #output
shoes,running

142 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Alessandro Galassi - Tuesday, 4 August 2020, 3:56 AM

I had some di culty with this assignment. please leave suggestions, feedback and maybe
some helpful information in the comments. I would highly appreciate it.
24 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Krista White - Tuesday, 4 August 2020, 8:14 AM

Hi Alessandro,

Good job. I agree this was kind of a tough assignment, not least because the
instructions were very broad. I learned something from this line: "print(f'{place}:


{medal}')", so thanks. Not entirely sure what the "f" means, but I take it this is a kind of
formatting method? It's a little bit easier to read the code than the typical way we've
/
been formatting strings so I like it In your last example what does " format(key=key
been formatting strings, so I like it. In your last example, what does .format(key key,
val=val))" do? Judging by the previous part I commented on, I would have thought you
would need a "f' " before the variable names, but I guess not? It seems to work ne

without it. Your formatting is really nice and easy to follow, which is de nitely
appreciated.
129 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Ndumiso Mkhize - Tuesday, 4 August 2020, 12:07 PM

Hi Alessandro

Thank you for the informative and easy to follow post, much appreciated and i to managed
to learn from it. I have noticed that when doing research about each of our units i do come
across di erent formatting styles and functions that does make the program look more
clean and formatted but not sure how to apply it, for example when you use the .format, i
have seen it used in other places but not sure whats its real function, but i guess as we
develop in the course we will learn things that will help us write more better programs.

Thank you again for the insightful post.


110 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Khai Lamh Cin - Wednesday, 5 August 2020, 11:52 AM

Hi Galassi, That was fantastic clear examples and nd a good point seeing each by each
exampels.
Thank You
19 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Khai Lamh Cin - Tuesday, 4 August 2020, 2:12 PM

Truples can be useful with loops over dictionaries in iterating within all over the dictionary
elements and it's useful with loops over listings to iterating two listings together in one loops. 

Example 


/
>>> databse = {'one':'tit', 'two':'nit', 'three':'tone', 'four':'lay'}
>>> database #verifying set dictionary work
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'database' is not defined
>>> database
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'database' is not defined
>>> databse #I've entered the wrong name so will see now
{'one': 'tit', 'two': 'nit', 'three': 'tone', 'four': 'lay'}
>>> #alright dictionary is working so will start with listing
>>> listing = list(databse.items()) #getting the key and values from databse
>>> listing #test listing
[('one', 'tit'), ('two', 'nit'), ('three', 'tone'), ('four', 'lay')]
>>> #alright listing fine so will go on with checking the tuples by two step printi
ng
>>> print('databse.items() = ',listing)
databse.items() = [('one', 'tit'), ('two', 'nit'), ('three', 'tone'), ('four', 'la
y')]
>>> print('Identifying databse.items() found ', type(listing[1]))
Identifying databse.items() found <class 'tuple'>
>>> #alright we got into a tuple
>>> for x,y in databse.items(): #this will loop over the dictionary elements
... print('The key found ', x, ', the value found ', y)
...
The key found one , the value found tit
The key found two , the value found nit
The key found three , the value found tone
The key found four , the value found lay
>>> #see truple can get over the dictionary and getting the format desired
>>> #let's try loop through two listings at once with truples
>>> firstList = [a,b,c,d,e]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> #forgot to add string type
>>> firstList = ['a',]
>>> firstList = ['a','b','c','d']
>>> #okay got our fist list
>>> secondList = ['e','f','g','h']
>>> #we will enumerate the above listings
>>> listingOne = enumerate(firstList)
>>> listingTwo = enumerate(secondList)


>>> firstList
['a', 'b', 'c', 'd']
>>> SecondList
/
Traceback (most recent call last):
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'SecondList' is not defined
>>> secondList
['e', 'f', 'g', 'h']
>>> listingOne
<enumerate object at 0x000002197C3664C0>
>>> ListingTwo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'ListingTwo' is not defined
>>> listingTwo
<enumerate object at 0x000002197C3660C0>
>>> zipping = list(zip(listingOne,listingTwo))
>>> print('zipping got ', zipping)
zipping got [((0, 'a'), (0, 'e')), ((1, 'b'), (1, 'f')), ((2, 'c'), (2, 'g')),
((3, 'd'), (3, 'h'))]
>>> #alright, let's finalize how we looping through the two listing with truples
>>> print('identifying zipping elements is ', type(zipping[1]))
identifying zipping elements is <class 'tuple'>
>>> #now you see we got truple
>>> for listingOne,listingTwo in zipping:
... print(listingOne, listingTwo)
...
(0, 'a') (0, 'e')
(1, 'b') (1, 'f')
(2, 'c') (2, 'g')
(3, 'd') (3, 'h')
>>> #see! we got a nice loop checking through the two listing at once
>>>

464 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Elad Tenenbom - Wednesday, 5 August 2020, 3:09 AM

I found your post very easy to read and understand, you did help me get the zip idea.
18 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Mafrikhul Muttaqin - Wednesday, 5 August 2020, 8:44 PM

Tuple (immutable) can be created directly or by using the list (mutable). We also can make a
dictionary using the tuple.  

/
# merging list using zip 
def weaponary(crew_name, crew_strength):
    weaponary = tuple(zip(crew_name, crew_strength))
    return weaponary 
crew_name = ["Luffy", "Zorro", "Sanji"] 
crew_strength = ["rubber", "sword", "leg"] 
print(weaponary(crew_name, crew_strength)) 
# output :
# (('Luffy', 'rubber'), ('Zorro', 'sword'), ('Sanji', 'leg'))
# zip function able to merge lists and changed it into tuple

# enumerate function --> making index


# packing a tuple
crew_pack_tuple = "Robin" , "Franky"
crew_job = "archeologist" , "carpenter"
for i,a in enumerate(crew_pack_tuple):
    crew_job = crew_job[i]
    print(i, "is", a)
# output : 
# 0 is Robin
# 1 is Franky
# By using the enumerate() function, Python can make an index to each item in
a tuple (iterable object), it will make tracking that objects easier.

# item method
# directly making a tuple dictionary
weapon_dictionary = {"Luffy" : "rubber", "Zorro" : "sword" , "Sanji" : "leg"
, "Nami" : "weather" , "Usshop" : "slingshot"}
print(weapon_dictionary.items())
# output :
# dict_items([('Luffy', 'rubber'), ('Zorro', 'sword'), ('Sanji', 'leg'), ('Na
mi', 'weather'), ('Usshop', 'slingshot')])
# items() function here is used to give back the list with all dictionary val
ues

185 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Nabeel Fahim - Wednesday, 5 August 2020, 11:53 PM

Hi Mafrikhul

Well done!
I actually liked how you used short explanations for all important places in the code. All

/
requirements were properly addresed!
requirements were properly addresed!

BR

25 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 7


by Nabeel Fahim - Wednesday, 5 August 2020, 11:34 PM

0 words

Permalink Show parent

◀ Learning Guide Unit 7


Jump to...

Programming Assign. 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 this clock.

Wed, Aug 19, 2020


9:03 pm

Disclaimer Regarding Use of Course Material  - Terms of Use


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

    
Reset user tour on this page


/

You might also like