Tuples are similar to lists, but are immutable, which means once defined they cannot be changed
Create tuples using parentheses ()
and separating by commas:
Access individual tuple elements via their index, just as you'd do with list elements (index-based, 0 starting position):
Fewer operations relative to List construct which is mutable, tuples restricted because they're defined as immutable. Main relevant for common or more basic types given context
Operation/Method | Description | Example |
---|---|---|
+ |
Concatenate/sum/join Tuples. Does not change initial or overwrite values rather like sum using integers but with new object from resultant joined sequence from all tuples joined/summed by that step where earlier Tuple values untouched in-place |
tuple1 = (1, 2, 3)
|
* |
Replicates |
mytuple= (1,2)*3
|
count() |
Returns number of element occurrences exactly the same as with List approach but operates over tuples not List instances | my_tuple.count(1) . Like example below counts everything only ever given for whatever valid data or types defined given context so always number regardless what stored for `count` example and use in method application with appropriate type even if elements repeated. It counts the repetition too unlike `index()` which would otherwise serve better, assuming positional uniqueness or handling collisions or such, especially when applied repeatedly within nested looping contexts if appropriate
numbers = (1, 2, 2, 3, 2, 4, 5, 2)
count_of_2 = numbers.count(2) print(count_of_2) # Output: 4 (as seen from our data sequence initially) |
index() |
returns first index, does not modify rather only returns indice where element is found after scan similar as for count case |
vowels=("a", "e", "i", "o", "i", "u")
|