In Python, a tuple is an immutable sequence data type that can contain elements of different types. Tuples are similar to lists, but they are defined using parentheses instead of square brackets.
Here is an example of defining a tuple in Python:
1 2 3 |
Copy code<code># Define a tuple with three elements t = (1, 'a', 3.14) |
You can access the elements of a tuple using indices, just like with a list. For example:
1 2 3 4 5 6 |
Copy code<code># Get the first element of the tuple print(t[0]) # Get the second element of the tuple print(t[1]) |
You can also use the len
function to get the length of a tuple. For example:
1 2 3 |
Copy code<code># Get the length of the tuple print(len(t)) |
To pack variables into a tuple, you can use the tuple
function. For example:
1 2 3 4 5 |
Copy code<code># Pack three variables into a tuple x = 1 y = 'a' z = 3.14 t = tuple((x, y, z)) |
To unpack a tuple into variables, you can use the assignment operator. For example:
1 2 3 |
Copy code<code># Unpack the elements of a tuple into variables x, y, z = (1, 'a', 3.14) |
You can compare tuples using the comparison operators. For example:
1 2 3 4 5 6 7 8 9 10 11 12 |
Copy code<code># Compare two tuples t1 = (1, 2, 3) t2 = (1, 2, 3) print(t1 == t2) # True print(t1 != t2) # False print(t1 < t2) # False print(t1 > t2) # False # Compare elements of a tuple print(1 in t1) # True print(4 in t1) # False |
You can slice a tuple using the slice notation. For example:
1 2 3 4 |
Copy code<code># Get a slice of a tuple t = (1, 2, 3, 4, 5) print(t[1:3]) # (2, 3) |
To delete a tuple, you can use the del
statement. For example:
1 2 3 4 |
Copy code<code># Delete a tuple t = (1, 2, 3) del t |
It’s important to note that once a tuple is deleted, it cannot be accessed or used in any way.
In Python, you can use tuples as keys in dictionaries, as long as the elements of the tuple are immutable. For example:
1 2 3 |
Copy code<code># Use a tuple as a dictionary key d = {(1, 2): 'a', (3, 4): 'b'} print(d[(1, 2)]) # 'a' |