0% found this document useful (0 votes)
3 views2 pages

Python Tuple

A tuple in Python is an immutable, ordered sequence of elements that cannot be modified after creation, distinguished by its use of parentheses. Tuples can store heterogeneous data types and support limited operations such as concatenation, replication, and slicing. They are preferred over lists for data security, performance, and as dictionary keys.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Python Tuple

A tuple in Python is an immutable, ordered sequence of elements that cannot be modified after creation, distinguished by its use of parentheses. Tuples can store heterogeneous data types and support limited operations such as concatenation, replication, and slicing. They are preferred over lists for data security, performance, and as dictionary keys.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

In Python, a Tuple is an immutable, ordered sequence of elements.

While similar
to lists, the key difference is that once a tuple is created, its elements cannot be
changed, added or removed.
1. Core Concepts

●​ Immutability: Unlike lists, you cannot perform "in-place" changes (No append,
extend, or item assignment).

●​ Notation: Defined using parentheses () instead of square brackets [].


●​ Heterogeneous: Can store elements of different data types together (e.g., (1,
"Apple", 3.14)).

2. Creation & Types

●​ Empty Tuple: T = ().


●​ Single Element Tuple: Must include a trailing comma, e.g., T = (5,). Without
the comma, Python treats (5) as a regular integer.
●​ Tuple Packing: Assigning multiple values to a single variable: T = 1, 2, 3.
●​ Tuple Unpacking: Assigning tuple values to multiple variables: a, b, c = T.

3. Operations & Methods


Since tuples are immutable, they only support a few built-in methods compared to lists:

Operation/Method Description

Concatenation (+) Joins two tuples to create a new one.

Replication (*) Repeats the tuple elements n times.

Slicing Extracts a sub-part: T[start:stop:step].

len(T) Returns total number of elements.


count(x) Returns the number of times x appears.

index(x) Returns the first index of value x.

max() / min() Returns highest/lowest value (elements must be of same type).

sum() Returns the sum of numeric elements.

4. Why Use Tuples Instead of Lists?

●​ Data Security: Protects data from accidental modification.


●​ Performance: Generally faster to iterate through than lists.
●​ Dictionary Keys: Tuples can be used as keys in a dictionary (if they contain only
immutable elements), whereas lists cannot.

You might also like