How to Use Tuples in Python


In this example, we will learn the methods to use tuples in Python.

2. Tips

Tuple creation is very simple, just adding elements in parentheses and separating them with commas.

3. Define Tuple

#!/usr/bin/python
# -*- coding: UTF-8 -*-

tup = ('Hello', 'World', '!', 'Have a good day', 8, 5)

4. Access Tuple

Tuples can use the index to access values, as shown in the following example:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

tup1 = ('Google', 2013, 'Yahoo', 2015)
tup2 = (1, 2, 3, 4, 5, 6, 7)

print("tup1[0]: ", tup1[0])
print("tup2[1:5]: ", tup2[1:5])

Output:

tup1[2]:  Yahoo
tup2[1:5]:  (2, 3, 4, 5)

5. Modify Tuple

The element values in the tuple are not allowed to be modified. We can delete the tuples, as shown in the following example:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

tup = ('Google', 'Yahoo', 1997, 2000)
print(tup)
del tup;
print(tup)

Output:

('Google', 'Yahoo', 1997, 2000)
NameError: name 'tup' is not defined

6. Convert List to Tuple

We can easily convert list to tuple by simply using tuple(list_name), below is an example:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

list1= ['Google', 'Yahoo', 'Amazon', 'Facebook']
print(list1)
tuple1=tuple(list1)
print(tuple1)

Output:

['Google', 'Yahoo', 'Amazon', 'Facebook']
('Google', 'Yahoo', 'Amazon', 'Facebook')
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement