Python Tuple

Tuple

Tuples are used to store multiple items in a single variable.

Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage.

A tuple is a collection which is ordered and unchangeable.

Tuples are written with round brackets.

Example

Create a Tuple:

 
thistuple = ("apple", "banana", "cherry")

print(thistuple)

Tuple Items

Tuple items are ordered, unchangeable, and allow duplicate values.

Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered

When we say that tuples are ordered, it means that the items have a defined order, and that order will not change.

Unchangeable

Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.

Allow Duplicates

Since tuples are indexed, they can have items with the same value:

Example

Tuples allow duplicate values:

 
thistuple = ("apple", "banana", "cherry", "apple", "cherry")

print(thistuple)

Tuple Length

To determine how many items a tuple has, use the len() function:

Example

Print the number of items in the tuple:

 
thistuple = ("apple", "banana", "cherry")

print(len(thistuple))

Tuples in Python

A Tuple is a collection of Python objects separated by commas. In someways a tuple is similar to a list in terms of indexing, nested objects and repetition but a tuple is immutable unlike lists which are mutable.

Creating Tuples

 # An empty tuple
empty_tuple =()
print(empty_tuple)

Output:

  ()
 # Creating non-empty tuples
  
# One way of creation
tup ='python', 'geeks'
print(tup)
  
# Another for doing the same
tup =('python', 'geeks')
print(tup)

Output

 ('python', 'geeks')
('python', 'geeks')

Note: In case your generating a tuple with a single element, make sure to add a comma after the element.

 

Concatenation of Tuples

 # Code for concatenating 2 tuples
  
tuple1 =(0, 1, 2, 3)
tuple2 =('python', 'geek')
  
# Concatenating above two
print(tuple1 +tuple2)

Output:

 
(0, 1, 2, 3, 'python', 'geek')

 

Nesting of Tuples

 # Code for creating nested tuples
  
tuple1 =(0, 1, 2, 3)
tuple2 =('python', 'geek')
tuple3 =(tuple1, tuple2)
print(tuple3)

Output :

 ((0, 1, 2, 3), ('python', 'geek'))

 

Repetition in Tuples

 # Code to create a tuple with repetition
  
tuple3 =('python',)*3
print(tuple3)

Output

  ('python', 'python', 'python')

Try the above without a comma and check. You will get tuple3 as a string ‘pythonpythonpython’.

For more, checkout W3Schools and Geeks For Geeks.