For loops - Iterating Tuples#

Download exercises zip#

Let’s see some exercise about tuples.

Exercise - double couples#

✪ Given a lst with n integer numbers, places in res a NEW list which contains n tuples having each two elements. Every tuple contains a number taken from the corresponding position of the initial list, and its double.

For example - given:

lst = [ 5, 3, 8]

After your code it must result:

>>> print(res)
[(5,10), (3,6), (8,16)]
[ ]:
lst = [5,3,8]
#lst = [2,7]   # [(2,4),(7,14)]

res = []

# write here

Show solution

[ ]:
lst = [5,3,8]
#lst = [2,7]   # [(2,4),(7,14)]

res = []


for element in lst:
    res.append((element, element * 2))
print(res)

Exercise - carpet#

✪✪ Let’s call a touple a tuple with a couple of elements. Write some code which given a tuple t, produces a list having as elements touples each taken in alternation from t.

  • if the input tuple t has an odd number of elements, the last tuple in the list to return will be made of only one element

Example 1 - given:

>>> t = ('c', 'a', 'r', 'p', 'e', 't')    # even length

after your code it must result:

>>> print(res)
[('c', 'a'), ('r', 'p'), ('e', 't')]

Example 2 - given:

>>> t = ('s','p','i','d','e','r','s')     # odd length

After your code it must result:

>>>print(res)
[('s', 'p'), ('i', 'd'), ('e', 'r'), ('s',)]
[ ]:
t = ('c', 'a', 'r', 'p', 'e', 't')
#t = ('s','p','i','d','e','r','s')

# write here

Show solution

[ ]:
t = ('c', 'a', 'r', 'p', 'e', 't')
#t = ('s','p','i','d','e','r','s')

res = []
i = 0
for i in range(0,len(t)-1,2):
    res.append((t[i],t[i+1]))
if len(t) % 2 == 1:
    res.append((t[-1],))
print(res)

Continue#

Go on with For loops - Iterating Sets