Python – Tuples

In Pyhton, a tuple is similar to list except it is immutable and are written with optional round brackets.

A Tuple is:

  • immutable
  • ordered
  • heterogeneous
  • indexed (starts with zero)
  • written with round brackets (optional but recommneded)
  • is faster during iteration, since it is immutable

Tuples are useful for creating objects which generally contain related information e.g. employee information. In other words, a tuple lets us “chunk” together related information and use it as a single thing.

1. Creating a Tuple

Elements in tuples are enclosed in round brackets and separated with comma. Tuples can contain any number of items of different types.

Tuple = (item1, item2, item3)
tuple1 = ()		# empty tuple

tuple2 = (1, "2", 3.0)

tuple3 = 1, "2", 3.0

1.1. Tuple with one element

If the tuple contains only one element, then it’s not considered as a tuple. It should have a trailing comma to specify the interpreter that it’s a tuple.

tupleWithOneElement = ("hello", )	# Notice trailing comma

1.2. Nested Tuple

A tuple which contains another tuple as its element, it is called nested tuple.

nestedTuple = ("hello", ("python", "world"))

2. Accessing Tuple Items

We can access tuple items using indices inside square brackets.

  • Positive index begins counting from start of tuple.
  • Negative index begins counting from end of tuple.
  • A range of index will create a new tuple (called Slicing) with the specified items.
  • Range [m:n] means from position m (inclusive) to position n (exclusive).
  • Use double indexes to access the elements of nested tuple.
Tuple = ("a", "b", "c", "d", "e", "f")

print(Tuple[0])		# a
print(Tuple[1])		# b

print(Tuple[-1])	# f
print(Tuple[-2])	# e

print(Tuple[0:3])	# ('a', 'b', 'c')
print(Tuple[-3:-1])	# ('d', 'e')

Tuple = ("a", "b", "c", ("d", "e", "f"))

print(Tuple[3])			# ('d', 'e', 'f')
print(Tuple[3][0])		# d
print(Tuple[3][0:2])	# ('d', 'e')

3. Loop into tuple

Use a for loop for iterating through the tuple items.

Tuple = ("a", "b", "c")

for x in Tuple:
  print(x)

4. Check if an item exist in tuple

To check if a tuple contains a given element, we can use 'in' keyword and 'not in' keywords.

Tuple = ("a", "b", "c", "d", "e", "f")

if "a" in Tuple:
  print("Yes, 'a' is present")		# Yes, 'a' is present

if "p" not in Tuple:
  print("No, 'p' is not present")	# No, 'p' is not present

5. Sorting a Tuple

Use language in-built sorted() method for sorting the elements inside a tuple.

Tuple = ("a", "c", "b", "d", "f", "e")

sortedTuple = sorted(Tuple)

print (sortedTuple)	# ("a", "b", "c", "d", "e", "f")

6. Repetition and Concatenation of Tuples

To repeat all the elements of a tuple, multiply it by required factor N.

Tuple = ("a", "b") 

repeatedTuple = Tuple * 3

print (repeatedTuple)	# ('a', 'b', 'a', 'b', 'a', 'b')

To join/concatenate two or more tuples we can use the + operator.

Tuple1 = ("a", "b", "c") 
Tuple2 = ("d", "e", "f")

joinedTuple = Tuple1 + Tuple2

print (joinedTuple)	# ("a", "b", "c", "d", "e", "f")

7. Packing and Unpacking the Tuple

Packing is referred to as the operation where we assign a set of values to a variable. In packing, all items in the tuple are assigned to a single tuple object.

In below example, all three values are assigned to variable Tuple.

Tuple = ("a", "b", "c")

Unpacking is referred to as the operation where the tuple variable is assigned to another tuple and individual items in the tuple are assigned to individual variables.

In given example, Tuple is unpacked into new tuple and values "a", "b" and "c" – are assigned to variables x, y and z.

Tuple = ("a", "b", "c")		# Packing

(x, y, z) = Tuple

print (x)	# a
print (y)	# b
print (z)	# c

During unpacking, the number of elements in the tuple on the left of the assignment must equal the number on the right.

Tuple = ("a", "b", "c")		# Packing

(x, y, z) = Tuple		# ValueError: too many values to unpack (expected 2)

(x, y, z, i) =	Tuple 	# ValueError: not enough values to unpack (expected 4, got 3)

8. Named tuples

Python provides a special type of function called namedtuple() that comes from the collection module.

Named Tuples are similar to a dictionary but supports access from both the value and the key, where dictionary support access only by key.

import collections

Record = collections.namedtuple('Record', ['id', 'name', 'date'])

R1 = Record('1', 'My Record', '12/12/2020')

#Accessing using index
print("Record id is:", R1[0])		# Record id is: 1

# Accessing using key	
print("Record name is:", R1.name)	# Record name is: My Record

9. Python Tuples Methods

9.1. any()

Returns True if at least one element is present in the tuple and returns False if the tuple is empty.

print( any( () ) )		# Empty tuple - False
print( any( (1,) ) )	# One element tuple - True
print( any( (1, 2) ) )	# Regular tuple - True

9.2. min()

Returns the smallest element (Integer) of the Tuple.

Tuple = (4, 1, 2, 6, 9)

print( min( Tuple ) )	# 1

9.3. max()

Returns the largest element (Integer) of the Tuple.

Tuple = (4, 1, 2, 6, 9)

print( max( Tuple ) )	# 9

9.4. len()

Returns the length of the Tuple.

Tuple = (4, 1, 2, 6, 9)

print( len( Tuple ) )	# 5

9.5. sum()

Returns the sum of all elements (Integers) of the Tuples.

Tuple = (4, 1, 2, 6, 9)

print( sum( Tuple ) )	# 22

10. Conclusion

As discussed above, a tuple immutable, ordered and indexed collection of heterogeneous elements. It is written with or without round brackets.

Named tuples are very useful for creating object types and instances.

Tuples support operations similar to list type, only we cannot change the tuple elements.

Happy Learning !!

Read More :

Python – Tuples comparison
Python – Lists vs Tuples

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode