Tuple

  • A tuple is a collection which is ordered and unchangeable.
  • Tuples are written with round brackets.
  • It is a collection of objects which ordered and immutable.
  • Allow duplicate values

Create

Empty Tuple

empty_tuple = ()

print (empty_tuple)

Single Element

To write a tuple containing a single value you have to include a comma, even though there is only one value

x= (50,)

Multiple Element

x= ("apple", “54.23", “23", "apple", “India")


print(thistuple)

The Tuple() Constructor

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

x= tuple(("apple", “54.55",23))# note the double round-brackets

Read or Access

To access values in tuple, use the square brackets

For mutiple elements use slicing

X = (10,20,30)

X[0]

X[0:3] #Range of Indexes

You can use positive and negative index both.

Update

Tuples are unchangeable, that you cannot change, add, or remove items once the tuple is created.

tup1 = (12, 34.56)

# Following action is not valid for tuples

tup1[0] = 100 #throw Error

Delete

Tuples are immutable, so you cannot remove items from it.

del a[0] #throw error

#you can delete entire tuple

del a

Packing and unpacking

  • When we create a tuple, we normally assign values to it. This is called “packing” a tuple
  • we are also allowed to extract the values back into variables. This is called “unpacking“
x= ("apple", 53.36, 23)

(a, b, c) = x

#The number of variables must match the number of values in the tuple

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *