Python Tuples: Essential Concepts and Operations

Classified in Computers

Written on in 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

Comparison (<, >, <=, >=)

Compares tuples lexicographically.
Example: (1, 2) < (1, 3) Output: True

Membership

Checks if an element exists in the tuple.
Example: 1 in (1, 2, 3) Output: True

Concatenation

Combines two tuples into one.
Example: (1, 2) + (3, 4) Output: (1, 2, 3, 4)

Maximum

Returns the largest element in the tuple.
Example: my_tuple = (10, 20, 30, 5); print(max(my_tuple)) Output: 30

Minimum

Returns the smallest element in the tuple.
Example: my_tuple = (10, 20, 30, 5); print(min(my_tuple)) Output: 5

Conversion

Converts an iterable (like a list or string) into a tuple.
Example: my_list = [1, 2, 3, 4]; my_tuple = tuple(my_list); print(my_tuple) Output: (1, 2, 3, 4)


Student Information

Name: Sri Varshini M
Class: 1 B.Sc. Computer Science
Roll No: 245114156

Related entries: