Python Tuples: Essential Concepts and Operations
Classified in Computers
Written on in
English with a size of 2.38 KB
Introduction to Tuples
- Immutable: Cannot be changed after creation.
- Syntax: Defined using parentheses ().
- Versatile: Can store multiple data types.
- Performance: Faster than lists due to immutability.
Common Use Cases for Tuples
- Returning multiple values: Functions can return multiple values as a tuple.
- Representing records: Ideal for structured data like names, ages, and addresses.
- Dictionary keys: Tuples can be used as keys in dictionaries.
Basic Tuple Operations
Length
Returns the number of elements in the tuple.
Example: len((1, 2, 3)) Output: 3
Repetition
Repeats the tuple a specified number of times.
Example: (1, 2) * 3 Output: (1, 2, 1, 2, 1, 2)
Iteration
Loop through elements of a tuple.
Example: for x in (1, 2, 3): print(x) Output: 1, 2, 3