Hello, welcome back! In today's session, we'll delve deeply into Python tuples. These are collections of ordered items, which allow us to group related variables together. A key attribute of tuples is their immutability: once a tuple is initialized, it remains constant, ensuring the preservation of the grouped items. Let's dive into Python tuples!
Tuples are collections that permit duplicate items, and their elements can be of any type. Importantly, they are both "ordered" and "immutable". Tuple values are enclosed within parentheses ()
, separated by commas.
Suppose we have a student, and we'd like to store their grade in a single variable for compact and clear code. Here's how we can do that:
Python1grade_mary = ("Mary", 95) # a tuple of two elements
If we need to store grades for multiple students, we can organize this into a list of tuples or a nested tuple:
Python1grades = [("Mary", 95), ("John", 80), ("Susan", 75), ("Steve", 85)] # list of tuples 2grades_tuple = ( ("Mary", 95), ("John", 80), ("Susan", 75), ("Steve", 85) ) # nested tuple 3 4print(grades) # Prints [('Mary', 95), ('John', 80), ('Susan', 75), ('Steve', 85)] 5print(grades_tuple) # Prints (('Mary', 95), ('John', 80), ('Susan', 75), ('Steve', 85))
Initializing tuples is a breeze; you just need to list comma-separated values within parentheses. You might be surprised to learn that even parentheses are optional! Python will still interpret the layer of grouped items as a tuple.
Python1numbers = (1, 2, 3, 4) # tuple of numbers 2pickles = ("gherkins", "dill", "bread and butter") # tuple of strings 3tuple_without_parentheses = 'apple', 'banana', 'cherry' # A tuple without parentheses 4print(tuple_without_parentheses) # Prints ('apple', 'banana', 'cherry')
Just as with a list, you can access elements in a tuple by using indexing. Additionally, we can access the elements from the end of the tuple by using negative indexing.
Python1pickles = ("gherkins", "dill", "bread and butter") 2print(pickles[0]) # Outputs: "gherkins" 3print(pickles[-1]) # Outputs: "bread and butter" 4print(pickles[0:2]) # Outputs: ("gherkins", "dill")
Unlike lists, tuples can't be altered once initialized. If you try to change an element inside a tuple, Python will raise a TypeError
.
Python1pickles[0] = "cornichons" # This will raise a TypeError.
Immutable data is favored in scenarios where consistency or data security is required. With tuples, the data maintains constancy over time, even when it's passed around different parts of your program.
Despite their immutability, you can execute various operations on tuples. For instance, we have:
+
): This merges two tuples to form a new one.*
): This duplicates a tuple a specified number of times.in
): This determines whether an item exists in a tuple.count
): This determines the number of occurrences of the provided element.index
): This determines the index of the first occurrence of the provided element.Python1numbers = (1, 2, 3) 2letters = ('a', 'b', 'c', 1) 3concatenation = numbers + letters # Concatenation; Outputs: (1, 2, 3, 'a', 'b', 'c', 1) 4concatenation_2 = numbers + (4,) # Special syntax to concatenate with a single-element tuple; Outputs (1, 2, 3, 4) 5repetition = numbers * 3 # Repetition; Outputs: (1, 2, 3, 1, 2, 3, 1, 2, 3) 6print('a' in numbers) # Membership; Outputs: False 7print(concatenation.count(1)) # Counting occurrences; Outputs: 2 8print(concatenation.index(1)) # Finding the first occurrence; Outputs: 0
Both lists and tuples serve unique purposes. While lists offer greater flexibility due to their mutability, tuples, being immutable, are preferred in situations where data constancy is critical. Depending on your application's requirements, you can choose to use either tuples or lists.
Well done! We've just toured Python tuples — how to create tuples, access tuple contents, and perform various operations on tuples. We've also compared tuples with lists and clarified when to use each. Ready for some practice? Let's solidify your understanding of tuples with exercises — remember, practice makes perfect!