Javascript Basics

Python Tuple

Python tuples are useful for listing elements (Objects). Tuple is quite similar to list but it has a difference. Tuple is slightly different than list.

(I have discussed about list in one of the previous chapter)

What is tuple?

Tuple is collection of elements or objects. Objects of tuples are ordered in certain sequence. Which means by using index number alike list, we can call any object that is present in tuple.

Example: fruitnames=(“orange”,”apple”,”Banana”,”pine apple”,”Grape”)

Difference between Tuple and List

In python, tuple and list are two different types of data variables. List elements can be changed using index number and assigning value. Where as tuple can not be changed. It is non changeable. Either we can add or delete object from tuple. List variable elements are assigned in between square brackets where as tuple objects are kept inside parenthesis.

How to declare an empty tuple?

In python programming, we often encounter a situation where we need to declare an empty tuple variable. So following is the way to declare it.

fruitnames=()

Remember

If you have to keep only one element in a tuple, then that element must end with a comma. Yes. In python tuple, if one element is there then it must end with a comma.

Example: fruitname=(“orange”,)

How to print  elements present in a tuple?

Similar to printing elements of list, that is calling its respective index number

Example

fruitnames=(“orange”,”apple”,”banana”)

print(fruitnames[0])

print(fruitnames[1])

print(fruitnames[2])

Output:

Orange

Apple

Banana

Concatenation of Tuples

One of the best feature about tuple in python, the elements of tuples can be combined with addition operator.

Example

fruitnames=(“Apple”,”Banana”,”Orange”)

fruitnames2=(“Pine Apple”,”Grape”,”Guava”)

newfruitnames=fruitnames+fruitnames2

print(newfruitnames)

Output: (“Apple”,”Banana”,”Orange”,”Pine Apple”,”Grape”,”Guava”)

How to calculate the number of objects or elements present in a tuple?

To calcualte the number of elements and objects present in a tuple, we use len function. Len function is python built function.

Example

fruitnames=(“orange”,”apple”,”banana”)

print(len(fruitnames))

Output:3