Python Tutorial | Python tuples 4

Changing a Tuple

* Unlike lists, tuples are immutable.

* This means that elements of a tuple cannot be changed once it has been assigned.
* But, if the element is itself a mutable data type like list, its nested items can be changed.
* We can also assign a tuple to different values (reassignment).

n=(0,1,2,3,4,5,6,7,8,9,10)
print(n)
#(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

n[1]=10
#error will get generated as tuple elements cannot be changed
print(n)

#but list within a tuple can be changed
n = (4, 2, 3, [6, 5])
print(n)
n[3][0]=10
print(n)
n[3][1]=100
print(n)

Output:
(4, 2, 3, [6, 5])
(4, 2, 3, [10, 5])
(4, 2, 3, [10, 100])

Concatenation and Repeat

* We can use + operator to combine two tuples. This is also called concatenation.

* We can also repeat the elements in a tuple for a given number of times using the * operator.

* Both + and * operations result into a new tuple.

Concatenation

Example:

# Concatenation
print((1, 2, 3) + (4, 5, 6))

Output:
(1, 2, 3, 4, 5, 6)

Example:
n1=(1,2,3,4,5)
print(n1)
n2=(6,7,8,9,10)
print(n2)
print(n1+n2)

Output:
#(1, 2, 3, 4, 5)
#(6, 7, 8, 9, 10)
#(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

Repeat

print((“Repeat”,) * 3)
# Output: (‘Repeat’, ‘Repeat’, ‘Repeat’)

n=(“hello”,)
print(n)
print(n*3)
print(n*5)

output:

(‘hello’,)
(‘hello’, ‘hello’, ‘hello’)
(‘hello’, ‘hello’, ‘hello’, ‘hello’, ‘hello’)

Deleting a Tuple

* As discussed above, we cannot change the elements in a tuple. That also means we cannot delete or remove items from a tuple.

* But deleting a tuple entirely is possible using the keyword del.

n=(1,2,3,4,5)
print(n)

del n[1]
#error : TypeError: ‘tuple’ object doesn’t support item deletion
print(n)

#But we can delete entire tuple
n=(1,2,3,4,5)
print(n)

del n
# NameError: name ‘n’ is not defined
File “C:/Python37/tup3.py”, line 4, in <module>
print(n)
NameError: name ‘n’ is not defined
print(n)

The tuple() Constructor

* It is also possible to use the tuple() constructor to make a tuple.

Example:

Using the tuple() method to make a tuple:

n=tuple((“amit”,”sumit”,”kapil”))
# note the double round-brackets
print(n)

Output:

(‘amit’, ‘sumit’, ‘kapil’)
>>>

n = tuple((“apple”, “banana”, “cherry”))
# note the double round-brackets
print(n)

Output:

(‘apple’, ‘banana’, ‘cherry’)
>>>

Python Basic Programming Tutorial

Python Introduction     Getting started in Python Programming      Python propgramming fundamentals     Python Operators    Python If Condition     Python for loop    Python range construct      Python While loop    break and continue statements     Different looping techniques     Python List     Python String     Python Functions    Python Inbuilt Functions     Python Recursion     Using Python Library     Python Tuples     Python Dictionary     Python Sets     Python Strings     Python Exception Handling     Python Data File Handling