tuples in python
TUPLE
The tuple data structure is used to store a group of data. The elements in this group are separated by a comma. Once created, the values of a tuple cannot change.
an empty tuple in python will be like this :
tuple = ()
A comma is required for a tuple with one item:
tuple = (5,)
The comma for one item may be counter intuitive, but without the comma for a single item, you cannot access the element. For multiple items, you do not have to put a comma at the end. This set is an example
info= ("anonymous", 20, "london")
The data inside a tuple can be of one or more data types such as text and numbers.
HOW ACCESS YOUR DATA ??
To access the data we can simply use an index. As usual, an index is a number between brackets:
#!/usr/bin/env python
Info = ("anonymous", 20, "london")
print(Info[0])
print(Info[1])
print(Info[0])
print(Info[1])
If you want to assign multiple variables at once, you can use tuples.
#!/usr/bin/env python
name,age,country,career = ('anonymous',20,'london','Computer')
print(country)
name,age,country,career = ('anonymous',20,'london','Computer')
print(country)
On the right side the tuple is written. Left of the operator equality operator are the corresponding output variables.
APPEND TO A TUPLE IN PYTHON !
If you have an existing tuple, you can append to it with the + operator. You can only append a tuple to an existing tuple.
#!/usr/bin/env python
x = (3,4,5,6)
x = x + (1,2,3)
print(x)
x = (3,4,5,6)
x = x + (1,2,3)
print(x)
Comments
Post a Comment