# Python: Tuple (Solutions)ΒΆ

1. Solutions:

couple_of_int = (0, 1)
print type(couple_of_int)            # tuple

couple_of_strings = ("one", "tuple")
print type(couple_of_strings)          # tuple

a_single_element = (0,)
print type(a_single_element)            # tuple
print len(a_single_element)             # 1

a_single_element_alt = tuple([0])
print type(a_single_element_alt)        # tuple
print len(a_single_element_alt)         # 1

wrong = (0)
print type(wrong)                   # int
print len(wrong)                    # error!

hundred_elements = tuple(range(100))
print type(hundred_elements)              # tuple

tuple_of_lists = (range(50), range(50, 100))
print type(tuple_of_lists)
print type(tuple_of_lists[0])

tuple_of_tuples = (tuple(range(50)), tuple(range(50, 100)))
print type(tuple_of_tuples)
print type(tuple_of_tuples[0])

2. Solutions:

l = [0, 1, 2]
t = (0, 1, 2)

# x refers to a list, the code replaces
# the first element with 100
x = l
x[0] = 100

# x now refers to a tuple, that is immutable:
# we cannot replace its elements, Python raises an error message
x = t
x[0] = 100                          # error!

3. Solutions:

tup = (0, 1, 2, [3, 4, 5], 6, 7, 8)

print tup[0]                      # 0
print type(tup[0])                # int

print tup[3]                      # [3, 4, 5]
print type(tup[3])                # list

print len(tup)                    # 9

print len(tup[3])                 # 3

tup[3][-1] = "last"
print tup
# yes, we can do it, we "modified" the tuple
# by modifying the list contained in it.

tup[-1] = "last"                # error!
# we cannot modify the tuple "directly"
# it's an immutable object