python logo

Tag: tuples

python tuple

The tuple data structure is used to store a group of data.  The elements in this group are separated by a comma. Once created, the values of a tuple cannot change.  

Related Course:
Python Programming Bootcamp: Go from zero to hero

Python Tuple

An empty tuple in Python would be defined as:

tuple = ()

A comma is required for a tuple with one item:

tuple = (3,)

The comma for one item may be counter intuitive,  but without the comma for a single item, you cannot access the element.  For multiple items, you do not have to put a comma at the end.  This set is an example:

personInfo = ("Diana", 32, "New York")

The data inside a tuple can be of one or more data types such as text and numbers.

Data access

To access the data we can simply use an index. As usual, an index is a number between brackets:

#!/usr/bin/env python

personInfo = ("Diana", 32, "New York")

If you want to assign multiple variables at once, you can use tuples:

#!/usr/bin/env python

name,age,country,career = ('Diana',32,'Canada','CompSci')

On the right side the tuple is written. Left of the operator  equality operator are the corresponding output variables.

Append to a tuple in Python

If you have an existing tuple, you can append to it with the + operator.  You can only append a tuple to an existing tuple.

#!/usr/bin/env python

x = (3,4,5,6)
x = x + (1,2,3)

If you are new to Python programming, I highly recommend this book.

Download Python Exercises