Skip to content

Python Tuples – Tutorial | Functions | Examples

  • by

Python Tuples: are very similar to Lists, the only difference is that tuples are not mutable, so you cannot change a tuple. Lists are used much more than tuples so tuples are only using very specific scenarios.

Python Tuples - Tutorial Functions Examples

tuple is a sequence of immutable Python objects (data structure). A tuple consists of a number of values separated by commas.

Python Tuples Syntax and Example

Here is syntax and simple example of Python Tuples.

tuples1 = ('Hello', 3.4, 2000)
tuples2 = ("One", "two", "three")
print(tuples1)
print(tuples2)

Output : (‘Hello’, 3.4, 2000)
(‘One’, ‘two’, ‘three’)

Tuples functions

Built-in functions like all()any()enumerate()len()max()min()sorted()tuple() etc. are commonly used with tuple to perform different tasks.

  • all() Return True if all elements of the tuple are true (or if the tuple is empty).
  • any() Return True if any element of the tuple is true. If the tuple is empty, return False.
tuples1 = (0, 1)
tuples2 = (0, 0)
tuples3 = (True, 0)
tuples4 = (True, False)
print(any(tuples1))
print(any(tuples2))
print(any(tuples3))
print(any(tuples4))

Output: True
False
True
True

Note: Any non-zero number or non-empty sequence evaluates to True.

  • enumerate() Return an enumerate object. It contains the index and value of all the items of a tuple as pairs.
tuples1 = (2, 6, 3, 8, 4, 1)
print(list(enumerate(tuples1)))

Output : [(0, 2), (1, 6), (2, 3), (3, 8), (4, 4), (5, 1)]

  • len() Return the length (the number of items) in the tuple.
tuples1 = (2, 6, 3, 8, 4, 1)
print(len(tuples1))

Output: 6

  • max() Return the largest item in the tuple.
tuples1 = (2, 6, 3, 8, 4, 1)
print(max(tuples1))

Output: 8

  • min() Return the smallest item in the tuple
tuples1 = (2, 6, 3, 8, 4, 1)
print(min(tuples1)

Output: 1

  • sorted() Take elements in the tuple and return a new sorted list (does not sort the tuple itself).
tuples1 = (2, 6, 3, 8, 4, 1)
print(sorted(tuples1))

Output : [1, 2, 3, 4, 6, 8]

  • sum() Retrun the sum of all elements in the tuple.
tuples1 = (2, 6, 3, 8, 4, 1)
print(sum(tuples1))

Output: 24

tuple() Convert an iterable (list, string, set, dictionary) to a tuple.

Do comment if you have any doubt in this tutorial.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All Examples of tuples & tuple functions are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading