Python Tuples – Tutorial | Functions | Examples

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.

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.

Output: 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.

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

  • len() Return the length (the number of items) in the tuple.

Output: 6

  • max() Return the largest item in the tuple.

Output: 8

  • min() Return the smallest item in the tuple

Output: 1

  • sorted() Take elements in the tuple and return a new sorted list (does not sort the tuple itself).

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

  • sum() Retrun the sum of all elements in the tuple.

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.