Python Tuples

Tuples are similar to lists, but are immutable, which means once defined they cannot be changed

1. Creating Tuples

Create tuples using parentheses () and separating by commas:

coordinates= () # creates empty Tuple
coordinates = (10, 20) # Tuple of integers
mixed_tuple = (1,"hello",3.14) #Tuple with mixed data types
single_element = (4,) #Single-element tuple requires a comma to distinguish from parenthesis used for expressions or operator precedence

2. Accessing Tuple items

Access individual tuple elements via their index, just as you'd do with list elements (index-based, 0 starting position):

mytuple = (1, 2, "Python", 5.7) print(mytuple[0]) # Access element 0 ( 1)
print(mytuple[2]) # Accesses element at index 2 ( "Python")
print(mytuple[-2]) # Negative indexing is also supported ( "Python")

3. Tuple Methods/Operations

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)
tuple2 = (4, 5, 6)
result_tuple = tuple1 + tuple2 print(result_tuple) #(1,2,3,4,5,6)
* Replicates mytuple= (1,2)*3
# result (1,2,1,2,1,2) new variable or can assign same one in-place without breaking rules related to "mutability"
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")
try:
index_of_i = vowels.index("i") # i position
print(index_of_i) # prints 2 because in the given Tuple ā€œiā€ occurs first at 2 indices i.e, at (2, 4) as noted
except ValueError: print("No such item in tuple structure currently defined")