Professional Documents
Culture Documents
Home
Home My courses CS 1101 - AY2020-T5 30 July - 5 August Discussion Forum Unit 7 DISCUSSION
ASSIGNMENT: UNIT 7
Search forums
The cut-o date for posting to this forum is reached so you can no longer post to it.
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.
51 words
Permalink
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
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
Dear Elad,
That was a good attempt, but more details and examples would have increased the quality
of your response. Consider Troycie's feedback.
Hi Elad. In this case you provides a good example for tuples and dictionaries
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
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
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
items = Dictionary1.items()
print(items)
#output
#Original Dictionary items:
#dict_items([('A', 'Boys'), ('B', 4), ('C', 'Girls')])
90 words
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
Good job with your examples Jonathan. But, I observed like Troycie mentioned that
your code for the zip function did not run.
22 words
do you have any idea why the zip function isnt working ?
11 words
/
Permalink Show parent
do you have any idea why the zip function isnt working ?
11 words
I think it should be ore like this, I just changed numbers and letters to n and l to
make it easier for me,
OUTPUT
[(1, 'a'), (2, 'b'), (3, 'c')]
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.
The most common use of zip is in a for loop . According to Downey, A. (2015):
>>> s = 'abc'
>>> t = [0, 1, 2]
REFERENCES
Downey, A. (2015). Think Python: How to think like a computer scientist. Needham,
Massachusetts: Green Tree Press.
132 words
Thanks Enrique
2 words
Thank you Enrique for the details given and for clarifying using the Jupyter and IDLE.
Regards,
Isaac Ayetuoma
18 words
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
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
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
Good work Troycie, you have taught me some new things about the items method that I
didn't know. Well done.
20 words
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
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)
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):
t=["George", "Elizabeth"]
t=list(zip(s,t))
OUTPUT
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)
t = d.items()
OUTPUT
REFERENCES
Downey, A. (2015). Think Python: How to think like a computer scientist. Needham,
Massachusetts: Green Tree Press.
/
308 words
Great Job Enrique. I love all the examples you use above,
11 words
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
Thanks for this clear post Enrique, I really enjoyed your format. Really well done and good
luck in the future.
20 words
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
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
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]
# 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
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.
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)
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
332 words
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
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)'''
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.
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'''
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
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
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
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
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)]
Hi Abubakar,
That was a simple solution, but feel we missed enumerate function to add.
Thanks
16 words
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]
/
if b != a**2:
check_squares(lyst, squares)
OUTPUT
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
def check_npa(d):
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
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
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
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.
>>> 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
0: gold #output
1: silver
2: bronze
gloves,boxing #output
shoes,running
142 words
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
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
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.
Hi Galassi, That was fantastic clear examples and nd a good point seeing each by each
exampels.
Thank You
19 words
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
I found your post very easy to read and understand, you did help me get the zip idea.
18 words
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
# 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
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
0 words
/
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.
Reset user tour on this page
/