Saturday, February 9, 2019

Python Tuples

A tuple in Python is a collection of data that is written within round brackets. Tuples are ordered collection of data, which means its has an index for every element. A tuple once created cannot be modified.

Creating a tuple:

We can create a tuple in the following way.

colorTuple = ("red","green","blue")
print(colorTuple)

Accessing tuple items:

The following will print 'green'. The index starts from 0, hence the element at index 1 is 'green'.

colorTuple = ("red","green","blue")
print(colorTuple[1])

Adding, Removing and Changing tuple items:

Items in tuples cannot be added, removed, changed or modified.

Tuple Length:

The len() function can be used to find the number of items in a tuple.

colorTuple = ("red","green","blue")
print(len(colorTuple))

Traversing through the items in a tuple:

This will print all the items in the tuple, one by one.

colorTuple = ("red","green","blue")
for x in colorTuple:
    print(x)

Checking if a tuple contains an item:

This following code will check if colorTuple contains green.

colorTuple = ("red","green","blue")
if "green" in colorTuple:
    print('The color green is present in the tuple.')

No comments: