A tuple is
just like a list, consist of number of values separated by commas.
Differences
between tuple and list
a.
List
is mutable, where as tuple is immutable
b.
Tuple
can contain heterogeneous data, where as list usually contains homogeneous
data.
test.py
employee=(1, "Hari Krihsna", "Gurram", 12345.678) print(employee) print(employee[0]) print(employee[1]) print(employee[2]) print(employee[3])
$ python3
test.py
(1, 'Hari
Krihsna', 'Gurram', 12345.678)
1
Hari Krihsna
Gurram
12345.678
As you
observe above example, elements in tuple are enclosed in parenthesis. Eventhough
tuples are immutable, you can create tuples which contain mutable objects, such
as lists.
test.py
employee=(1, []) print(employee) employee[1].append(2) employee[1].append(4) employee[1].append(6) print(employee)
$ python3
test.py
(1, [])
(1, [2, 4,
6])
Packing and unpacking
You can
define tuples, without using parenthesis.
For example,
employee=1,
"Hari Krihsna", "Gurram", 12345.678
Above one is
the example of tuple packing.
id,
firstName, lastName, salary = employee
Above one is
an example of tuple unpacking. Sequence unpacking requires that there are as
many variables on the left side of the equals sign as there are elements in the
sequence.
test.py
employee=1, "Hari Krihsna", "Gurram", 12345.678 id, firstName, lastName, salary = employee print(id) print(firstName) print(lastName) print(salary)
$ python3
test.py
1
Hari Krihsna
Gurram
12345.678
Concatenate tuples
‘+’ operator
is used to concatenate tuples.
>>> tuple1=(1, "HI", 2, 45.65) >>> tuple2=("abcdef", 54, 67) >>> tuple3=tuple1+tuple2 >>> tuple3 (1, 'HI', 2, 45.65, 'abcdef', 54, 67)
Slicing
Just like
lists, you can access tuples using slice notation.
Example
|
Description
|
tuple[start:end]
|
Returns tuple
from index start (included) to end index (excluded).
|
tuple[:end]
|
Returns
tuple from index 0(included) to end index (excluded).
|
tuple[start:]
|
Return
tuple from index start to till end.
|
tuple[-2:]
|
Return elements
from 2nd last to end.
|
>>> tuple1 (1, 'HI', 2, 45.65) >>> tuple1[0:] (1, 'HI', 2, 45.65) >>> tuple1[:] (1, 'HI', 2, 45.65) >>> tuple1[:3] (1, 'HI', 2) >>> tuple1[2:5] (2, 45.65)
‘*’: Repeat tuple elements
‘*’ is the repetition operator, used to repeat the
elements of tuple.
>>> tuple1 (1, 'HI', 2, 45.65) >>> >>> tuple1*3 (1, 'HI', 2, 45.65, 1, 'HI', 2, 45.65, 1, 'HI', 2, 45.65) >>>
Remove tuple elements
As I said,
tuples are immutable, so it is not possible to remove elements from tuple. But
you can remove the entire tuple using del statement.
>>> tuple1=(1, "HI", 2, 45.65) >>> >>> del tuple1 >>> tuple1 Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'tuple1' is not defined
Observe the
output, an exception raised; this is because after deletion, tuple does not
exist any more.
No comments:
Post a Comment