In Python, a tuple is another commonly used data structure that is similar to a list, but with a few key differences. A tuple is an immutable ordered collection of elements, which can be of any data type. Once a tuple is created, its elements cannot be changed.
Here is an example of creating and working with a tuple in Python:
python # Create a tuple my_tuple = (1, 2, 3, "four", 5.0) # Access elements of the tuple print(my_tuple[0]) # Output: 1 print(my_tuple[3]) # Output: "four" # Iterate over the elements of the tuple for item in my_tuple: print(item)
In this example, a tuple called `my_tuple` is created with five elements of different data types. The `print()` function is used to access and output the first and fourth elements of the tuple. A `for` loop is used to iterate over the elements of the tuple and output them to the console.
Because tuples are immutable, they cannot be modified once they are created. However, you can create a new tuple by concatenating two or more tuples together. Here is an example:
python # Create two tuples tuple1 = (1, 2, 3) tuple2 = ("four", 5.0) # Concatenate the tuples new_tuple = tuple1 + tuple2 # Output the new tuple print(new_tuple) # Output: (1, 2, 3, "four", 5.0)
In this example, two tuples (`tuple1` and `tuple2`) are created, and then they are concatenated together using the `+` operator. The resulting tuple (`new_tuple`) contains all of the elements from both tuples.
Tuples in Python are useful for situations where you need an ordered collection of elements that cannot be modified. They are commonly used to represent fixed collections of data, such as the coordinates of a point in space or a date and time.