
Python Tuples Explained Simply (Immutable Sequences)
Tuples are ordered collections similar to lists, but they cannot be changed after creation. This makes them useful for data that should stay fixed. What is a tuple? A tuple is created with parentheses () and items separated by commas. coordinates = ( 10 , 20 ) colors = ( " red " , " green " , " blue " ) single_item = ( 5 ,) # Note the comma for one item You can also create a tuple without parentheses: point = 3 , 4 An empty tuple: empty_tuple = () Tuples can contain mixed types and are immutable. Accessing elements Use indexes just like lists (starting at 0). colors = ( " red " , " green " , " blue " ) print ( colors [ 0 ]) # red print ( colors [ - 1 ]) # blue Slicing works too: print ( colors [ 1 : 3 ]) # ("green", "blue") Why use tuples instead of lists? Tuples are immutable: you cannot add, remove, or change items. This protects data from accidental changes. Tuples are faster than lists. Tuples can be used as dictionary keys (lists cannot). Attempting to modify raises an error: colo
Continue reading on Dev.to Tutorial
Opens in a new tab


