Categories:Viewed: 3 - Published at: a few seconds ago

[ What if we put a mutable object into the immutable tuple ]

what if we put a mutable object into the immutable tuple

tup1 = ([],)
print('tup before: ', tup1)
tup1[0] += [1]

there are ways to modify the mutable contents of the tuple without raising the TypeError

tup = ([],)
print('tup before: ', tup)
tup[0].extend([1])
print('tup after: ', tup)

another way to append data to tuple

tup = ([],) print('tup before: ', tup) tup[0].append(1) print('tup after: ', tup)

Add tuples like numerics

my_tup = (1,)
my_tup += (4,)
my_tup = my_tup + (5,)
print(my_tup)

What happens "behind" the curtains is that the tuple is not modified, but a new object is generated every time, which will inherit the old "name tag":

my_tup = (1,)
print(id(my_tup))
my_tup += (4,)
print(id(my_tup))
my_tup = my_tup + (5,)
print(id(my_tup))

Create a plain list

def plainlist(n=100000):
    my_list = []
    for i in range(n):
        if i % 5 == 0:
            my_list.append(i)
    return my_list

Create a list comprehension

def listcompr(n=100000):
    my_list = [i for i in range(n) if i % 5 == 0]
    return my_list

### Create a Generator
def generator(n=100000):
    my_gen = (i for i in range(n) if i % 5 == 0)
    return my_gen

Generator using yield function

def generator_yield(n=100000):
    for i in range(n):
        if i % 5 == 0:
            yield i