0

Tuple Unpacking

I have a function called unpack_and_reverse that will accept one parameter, a tuple with at least three items. The function should return a new tuple with only the first three items, but listed in reverse order. #For example: # # a_tuple = ("a", "b", "c", "d", "e") # unpack_and_reverse(a_tuple) -> ("c", "b", "a") # #However, to do this, you should not access any value in #the tuple directly (e.g. with a_tuple[1]). Instead, you #should use tuple unpacking to unpack them into variables. #You also should not touch any items past the third item #in the tuple: use tuple slicing instead to only access #the first three. #Write your function here! def unpack_and_reverse(aTuple): (string1, string2, string3) = aTuple return(string3, string2, string1) # But I am getting this error below# CAn anyone advise. Traceback (most recent call last): File "PackRat.py", line 35, in <module> print(unpack_and_reverse(("a", "b", "c", "d", "e"))) File "PackRat.py", line 22, in unpack_and_reverse (string1, string2, string3) = aTuple ValueError: too many values to unpack (expected 3) Command exited with non-zero status 1

21st Sep 2020, 12:23 PM
NG_
NG_ - avatar
5 Answers
+ 6
Avinesh , the code sample looks a little bit strange to me, but it is according to the description of the task. First a tuple unpacking to individal variables is done, and in the next line a new tuple from these 3 variables is created and finally the new tuple is returned. What about this: (does this follow the rules for this code?) a_tuple = ("a", "b", "c", "d", "e") def unpack_tuple(tup): return tup[:3][::-1] print(unpack_tuple(a_tuple))
21st Sep 2020, 6:08 PM
Lothar
Lothar - avatar
+ 4
Is this what you are looking for? https://code.sololearn.com/cx8JZnhwW1nD/?ref=app
21st Sep 2020, 12:35 PM
Avinesh
Avinesh - avatar
+ 1
NG_ you're welcome.
21st Sep 2020, 1:28 PM
Avinesh
Avinesh - avatar
+ 1
Lothar definitely, it gets the result as well. All I tried is to pick his code and do some slight modifications. And yes, the creation of a new tuple is not necessary at all. I'm not in touch with Python much, just trying to help others in some way or the other. The code does show as how unpacking is done.
21st Sep 2020, 6:16 PM
Avinesh
Avinesh - avatar
0
Thank you so much.
21st Sep 2020, 1:23 PM
NG_
NG_ - avatar