Day 3 of #30-days-of-code
On day 3, of my 30 days of the python coding series, I learned about tuples in python. Just like lists in Python, tuples store items in a single variable.
The syntax of a tuple is:
names = ('Jane', 'John', 'Smith', 'Doe'), which differs from that of a list: names = ['Jane', 'John', 'Smith', 'Doe']. This is a syntax difference where in the case of tuples, the items are stored in round brackets unlike the square brackets in lists.
Tuples in Python allow the storage of different items or values from different data types that is, they can store booleans, integers, strings, and even floats. The syntax for this is:
personal_details = ('John is a boy', 23, True, 78.9). Here the variable personal_details contains the different data types and does not give any error.
In Python, tuples can be declared using the tuple constructor, that is, names = tuple(('John', 'Jack', 'Jake')).
An important point to note in tuples, however, is that tuples are immutable, that is, once values are declared, they cannot be changed. This is different from lists because, in lists, values can be changed later on after declaration.
names = ('Jane', 'John', 'Smith', 'Doe')
names[0] = 'Jacob
The output in the terminal is: TypeError: 'tuple' object does not support item assignment
The above piece of code declares the values of names into a tuple and then tries to change the value of the item in the index(0) from 'Jane' to 'Jacob', and when the code is run, it gives the TypeError, which states that tuples do not support re-assigning items or values.
We can try the above process with a list and see what the outcome will be.
names = ['Jane', 'John', 'Smith', 'Doe']
names[0] = 'Jacob'
print(names)
The output in the terminal is: ['Jacob', 'John', 'Smith', 'Doe']
We can see that the value of the item in the index(0) gets changed from 'Jane' to 'Jacob'.