TUPLE DATA TYPE IN PYTHON:
A tuple is an ordered, immutable collection of elements in Python. Tuples are often used to store multiple related pieces of information in a single structure.
Here are some key points about tuples in Python:
Syntax: Tuples are defined by enclosing a comma-separated list of elements within parentheses. For example: (1, 2, 3, 4).
Immutable: Once a tuple is created, its elements cannot be changed. This makes tuples ideal for storing data that should not be modified.
Indexing: Tuples can be indexed just like lists, with the first element having an index of 0. For example: t = (1, 2, 3); t[1] would return 2.
Slicing: Tuples can be sliced just like lists, using the square bracket syntax. For example: t = (1, 2, 3); t[0:2] would return (1, 2).
Nesting: Tuples can contain elements of any data type, including other tuples. For example: t = ((1, 2), (3, 4)); t[0] would return (1, 2).
Unpacking: Tuples can be unpacked into individual variables. For example: t = (1, 2, 3); a, b, c = t; would assign the values 1, 2, and 3 to variables a, b, and c, respectively.
Comparison: Tuples can be compared to each other, with the comparison being based on the elements in the tuples. For example: (1, 2) < (3, 4) would return True.
Examples:
# Creating a tuple t = (1, 2, 3, 4) print(t) # Accessing elements in a tuple print(t[0]) # Output: 1 # Slicing a tuple print(t[0:2]) # Output: (1, 2) # Nesting tuples t = ((1, 2), (3, 4)) print(t[0]) # Output: (1, 2) # Unpacking tuples t = (1, 2, 3) a, b, c = t print(a, b, c) # Output: 1 2 3 # Comparison of tuples print((1, 2) < (3, 4)) # Output: True
BY ITSBILYAT
Comments
Post a Comment