DevAcademia
C++C#CPythonJava
  • Python Fundamentals

  • Introduction to Python
  • Getting Started with Python
  • Python Syntax
  • Python Comments
  • Python Variables
  • Python Data Types
  • Python Numbers
  • Python Casting
  • Python Strings
  • Python Booleans
  • Python Operators
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python If...Else
  • Python Match
  • Python While Loops
  • Python For Loops
  • Python Functions
  • Python Lambda
  • Python Arrays
  • Python OOP

  • Python OOP
  • Python Constructors
  • Python Destructors
  • Python Classes/Objects
  • Python Inheritance
  • Python Polymorphism
  • Python Quiz

  • Python Fundamentals Quiz
  • Python Fundamentals

  • Introduction to Python
  • Getting Started with Python
  • Python Syntax
  • Python Comments
  • Python Variables
  • Python Data Types
  • Python Numbers
  • Python Casting
  • Python Strings
  • Python Booleans
  • Python Operators
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python If...Else
  • Python Match
  • Python While Loops
  • Python For Loops
  • Python Functions
  • Python Lambda
  • Python Arrays
  • Python OOP

  • Python OOP
  • Python Constructors
  • Python Destructors
  • Python Classes/Objects
  • Python Inheritance
  • Python Polymorphism
  • Python Quiz

  • Python Fundamentals Quiz

Loading Python tutorial…

Loading content
Python FundamentalsTopic 36 of 77
←PreviousPrevNextNext→

Python Tuples

Tuple Fundamentals

Tuples are immutable sequences in Python that act as fixed collections of items. They are useful when data should not change after creation.

Key characteristics:

- **Immutable**: Elements cannot be modified, added, or removed

- **Ordered**: Preserve insertion order

- **Heterogeneous**: Can contain different data types

- **Hashable**: Usable as dictionary keys if all elements are hashable

- **Memory Efficient**: Use less memory than lists of the same size

- **Fixed-Length**: Often represent structured data with positional meaning

Example
# Tuple creation examples
empty_tuple = ()
single_elem = (42,)  # Single-element tuple requires comma
coordinates = 10.5, -72.3  # Parentheses optional
person = ('John', 32, 'Engineer', True)
matrix = ((1, 2), (3, 4))  # Nested tuples

# Tuple unpacking
name, age, occupation, is_active = person
Output
# Variables assigned: John, 32, Engineer, True
ℹ️ Note: The comma creates a tuple, not the parentheses. Empty tuples require parentheses.

Memory and Performance

Tuples are lightweight compared to lists due to immutability:

- **Fixed Allocation**: Tuples allocate exact memory needed

- **No Overallocation**: Lists over-allocate for growth, tuples don’t

- **Efficient Iteration**: Tuples iterate slightly faster

- **Literal Optimization**: Tuple literals may be folded at compile time

⚠️ Warning: Tuple creation is faster, but element access times are essentially the same as lists.
Example
import sys
from timeit import timeit

lst = [1, 2, 3, 4, 5]
tpl = (1, 2, 3, 4, 5)
print(f"List size: {sys.getsizeof(lst)} bytes")
print(f"Tuple size: {sys.getsizeof(tpl)} bytes")

print("List literal:", timeit('[1,2,3,4,5]', number=1000000))
print("Tuple literal:", timeit('(1,2,3,4,5)', number=1000000))
Output
List size: 96 bytes
Tuple size: 80 bytes
List literal: 0.12 sec
Tuple literal: 0.04 sec

Advanced Tuple Patterns

Tuples support powerful usage patterns:

- **Multiple Return Values**: Functions can return multiple results as tuples

- **Data Records**: Represent rows or structured records

- **Dictionary Keys**: Tuples can serve as composite keys

- **Argument Unpacking**: The * operator unpacks tuples into arguments

- **Value Swapping**: Clean, Pythonic variable swapping

Example
# Function returning multiple values
def get_stats(data):
    return min(data), max(data), sum(data)/len(data)

# Tuples as dictionary keys
locations = {}
locations[(40.7128, -74.0060)] = "New York"

# Argument unpacking
def vector_length(x, y, z):
    return (x**2 + y**2 + z**2)**0.5

point = (3, 4, 5)
print(vector_length(*point))  # 7.071...

# Swapping values
a, b = 10, 20
a, b = b, a
Output
7.0710678118654755

Real-world Applications

Use CaseExampleBenefits
ConfigurationDIMENSIONS = (1920, 1080)Immutable fixed settings
Database Recordsrow = (1, 'John', '1990-01-01')Predictable structure
Coordinatespoint = (x, y, z)Natural representation
Function Argumentsargs = (2, True, 'default')Convenient unpacking
Version Numbersversion = (3, 9, 1)Supports comparisons
Test your knowledge: Python Tuples
Quiz Configuration
4 of 8 questions
Sequential
Previous allowed
Review enabled
Early close allowed
Estimated time: 5 min
Python FundamentalsTopic 36 of 77
←PreviousPrevNextNext→