Tuples in Python

Python Tuples: In this tutorial, we will learn the basic concepts of Tuples in Python programming language with some examples.
Submitted by Bipin Kumar, on October 19, 2019

Python Tuples

Tuples in Python are a collection of elements in a round bracket() or not but separated by commas. Tuples are similar to list in some operations like indexing, concatenation, etc. but lists are mutable whereas tuples are immutable acts like a string. In Python, Tuples are converted into lists by using the keyword list and list are converted into tuples by using keyword "tuple".

Here we will see some examples to understand how to create tuples?, convert lists into tuples?, concatenation of tuples, nested tuples, etc.

Creating Tuples

t='Python','Tuple','Lists'
t2=('Python','Tuple','Lists','Includehelp','best')

e_t=()

u_l_t=('includehelp',)

print('empty tuple:',e_t)
print('Unit length tuple:',u_l_t)
print('first tuple:',t)
print('Second tuple:',t2)

Note: When you are going to create a tuple of length 1 in Python then you must put a comma after the element before closing the round brackets.

Output

empty tuple: ()
Unit length tuple: ('includehelp',)
first tuple: ('Python', 'Tuple', 'Lists')
Second tuple: ('Python', 'Tuple', 'Lists', 'Includehelp', 'best')

Here, we have seen that if we are creating tuples with round brackets or not both results are the same.

Concatenation of Tuples

We can simply add tuples like lists by using plus (+) sign between it. Let's suppose the same tuples that we have created just above and try to add these tuples.

Program:

t  = 'Python','Tuple','Lists'
t2 = ('Python','Tuple','Lists','Includehelp','best')

print('Concatenation of Tuples:\n',t+t2)

Output

Concatenation of Tuples: 
('Python', 'Tuple', 'Lists', 'Python', 'Tuple', 'Lists', 'Includehelp', 'best')

Convert list into tuples and tuples into list

t=('Python','Tuple','Lists','Includehelp','best')

l=list(t) #now l is list.
t2=tuple(l) #Here list is converted into tuple.

print('tuple is converted into list:',t)
print('list is converted into tuple:',t2)

Output

tuple is converted into list: ['Python', 'Tuple', 'Lists', 'Includehelp', 'best']
list is converted into tuple: ('Python','Tuple','Lists','Includehelp','best')

Nested tuples

Nested tuples means one tuple inside another like nested lists. To create a nested tuple, we have to simply put both or more tuples in the round brackets separated with commas. Again we will assume the same tuple that we have created above and try to make it in the form of a nested tuple. Let's look at the program,

t='Python','Tuple','Lists'
t2=('Python','Tuple','Lists','Includehelp','best')

nested_t=(t,t2)

print('Nested tuple:',nested_t)

Output

Nested tuple: (('Python', 'Tuple', 'Lists'), ('Python', 'Tuple', 'Lists', 'Includehelp', 'best'))


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.