Tuple Flashcards
Tuple
Just like a list but Immutable: Once a tuple is created, you cannot change its values.
Ordered: Tuples maintain the order of elements.
Indexable: Elements can be accessed by their index.
Allow Duplicates: Tuples can have multiple elements with the same value.
Create tuple
~~~
my_tuple = (1, 2, 3)
single_element_tuple = (4,)
```
Comma is necessary for a single element
another_tuple = 5, 6, 7
tuple can be created without () just values separated by comma
Accessing element
print(my_tuple[0]) # Output: 1
Tuple unpacking
x, y, z = my_tuple
Tuples support an operation known as “tuple unpacking” where you can assign the values from a tuple into multiple variables in a single statement.
Tuple methods
Concatenation: You can concatenate tuples using the + operator.
Repetition: Tuples can be repeated using the * operator.
Membership Test: Use in to check if an item exists in a tuple.
. len() to find the number of items in a tuple.
.index(value) to find the first occurrence of value.
.count(value) to count the number of occurrences of value.