Manipulations sur les tuples

by Joseph Razik, on 2019-10-18
tuples

Quelques manipulations sur les tuples et les références

In [1]:
# on créé 3 variables chaines de caractères
a = 1
b = 2
c = 3
print(id(a), a)
print(id(b), b)
print(id(c), c)
140719146585824 1
140719146585856 2
140719146585888 3
In [2]:
# on définit un tuple avec ces variables 
t = (a, b, c)
print(t)
(1, 2, 3)
In [3]:
# on essait d'insérer un élément ou changer ou élément du tuple
try:
    t[0] = 4
except TypeError as e:
    print('Erreur: ', e)
# impossible

try:
    t.append(4)
except AttributeError as e:
    print('Erreur: ', e)
try:
    t.add(4)
except AttributeError as e:
    print('Erreur: ', e)
# les fonctions n'existent pas
Erreur:  'tuple' object does not support item assignment
Erreur:  'tuple' object has no attribute 'append'
Erreur:  'tuple' object has no attribute 'add'
In [4]:
# on modifie une des variables du tuple
a = 4
print(id(a), a)
print(t)
140719146585920 4
(1, 2, 3)

le tuple t a gardé son ancienne valeur (voir le notebook sur la manipulation des ensembles

Maintenant avec des objets

In [5]:
class A:
    def __init__(self, pa):
        self.a = pa
In [6]:
a = A(1)
b = A(2)
print(id(a), a, a.a)
print(id(b), b, b.a)
140718788299632 <__main__.A object at 0x7ffba563cb70> 1
140718788299688 <__main__.A object at 0x7ffba563cba8> 2
In [7]:
t = (a, b)
print(t)
(<__main__.A object at 0x7ffba563cb70>, <__main__.A object at 0x7ffba563cba8>)
In [8]:
b = a
print(id(b), b, b.a)
print(t)
140718788299632 <__main__.A object at 0x7ffba563cb70> 1
(<__main__.A object at 0x7ffba563cb70>, <__main__.A object at 0x7ffba563cba8>)
In [9]:
b = t[1]
print(id(b), b, b.a)
140718788299688 <__main__.A object at 0x7ffba563cba8> 2
In [10]:
b.a = 3
print(t)
(<__main__.A object at 0x7ffba563cb70>, <__main__.A object at 0x7ffba563cba8>)
In [11]:
print(t[1].a)
3