For loops 4 - iterating tuples

Download exercises zip

Browse file online

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)]
Show solution
[2]:

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

res = []

# write here


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',)]
Show solution
[3]:

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

# write here


Continue

Go on with iterating sets

[ ]: