Use Python’s tuple() function to create tuples
In Python, a tuple is an immutable sequence type. It is similar to a list, but cannot be modified in any way. You can create tuples by using the tuple() function. This article explains how to use this function to create tuples, along with some code examples.
my_tuple = tuple() print(my_tuple)
The output result is an empty tuple: ()
my_tuple = tuple([1, 2, 3, 4, 5]) print(my_tuple)
The output result is: (1, 2, 3, 4, 5)
You can also add multiple elements to the tuple at one time:
my_tuple = tuple(["apple", "banana", "orange"]) print(my_tuple)
The output result is: ('apple', 'banana', 'orange')
my_tuple = tuple([1, 2, 3, 4, 5]) a, b, c, d, e = my_tuple print(a, b, c, d, e)
The output result is: 1 2 3 4 5
In this way, we assign each element in the tuple to the variables a, b, c, d, e.
def get_values(): name = "John" age = 25 country = "USA" return tuple([name, age, country]) result = get_values() print(result)
The output result is: ('John', 25, 'USA')
In the above example, we combine name, age, country into a tuple, and use it as the return value of the function.
Summary:
This article introduces how to use Python’s tuple() function to create tuples. With this function, you can create empty tuples, tuples with elements, unpack tuples, and return tuples as function returns. Tuple is an immutable sequence type suitable for representing some unmodifiable data collection. Using the tuple() function, you can easily create and manipulate tuples.
I hope this article will help you learn how to use the tuple() function to create tuples!
The above is the detailed content of Create tuples using Python's tuple() function. For more information, please follow other related articles on the PHP Chinese website!