onsdag 28 december 2022

Multiplication of sequences like lists, tuples and str | Python

The multiplication operator on a ordered collection (sequence), like strings, lists, tuples, byte sequences or byte arrays means that the items/objects inside are repeated. It does not mean creation of copies (shallow or deep ones) of the items/objects.

This can be tested with the help of the id() function which returns the memory address of an object. Two objects with overlapping lifetime can never have the same id.

An exception to this is small intergers and other immutables, which Python keeps a small cache of hence giving them the same ID.


Example 1:

```

a = [1]

b = [1]

print(id(a), id(b))

```

Output: 2 different IDs because no cashing. 


Example 1.1:

```

a = 1

b = 1

print(id(a), id(b))

```

Output: Same ID for a and b, because of cashing.


Example 1.2 Same ID because of repeat:

```

a = [1]

# Multiply by 2 to get [1, 1]

a = a * 2 

for num in a:

    print(id(a))

```

Output: (Same ID x 2):

140719374866624

140719374866624