Tuple in Python

This blogs describes tuple in python

It is a sequence which stores group of elements
Similar to list
Main difference between list and tuple is that once tuple is created, we cannot modify its elements
Tuple is immutable
Can’t able to use operation such as append(), remove(), insert(), pop() with tuple

Creating Tuple

Create a tuple by writing elements inside parenthesis.
Each element is separated by comma

tup = (10,20,30,40)

In the above example, tuple tup is created with 4 elements. Each element is separated by comma. These elements are enclosed in parenthesis.

Create a empty tuple

tup = ()

Empty tuple does not include any element.

Create a tuple with elements of multiple datatype

tup  = (10,'Mumbai',300)

Above tuple include integer and string datatype elements

Tuple with single element. Observe comma after the single element

tup =(20,)

If we do not mention parenthesis while writing element and each element is separated by command then by default it is taken as tuple

tup = 10,20,30,40,50

Tuple can also created by list. This is done by converting list into tuple using tuple() function

list = [1,2,3,4,5]
tup = tuple(list)
print(tup)

Output

(1, 2, 3, 4, 5)

Tuple can also be created by using range() function. Below code create a tuple with the stepsize of 3

tup1 = tuple(range(1,10,3))
print(tup1)

Output

(1, 4, 7)

Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s