Home  >  Article  >  Backend Development  >  Create tuples using Python's tuple() function

Create tuples using Python's tuple() function

WBOY
WBOYOriginal
2023-08-22 12:25:502256browse

Create tuples using Pythons tuple() function

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.

  1. Create an empty tuple
    Through the tuple() function, you can create an empty tuple. The sample code is as follows:
my_tuple = tuple()
print(my_tuple)

The output result is an empty tuple: ()

  1. Create a tuple containing elements
    Use the tuple() function, you It is possible to create tuples containing some elements.
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')

  1. Tuple unpacking
    Tuple unpacking is to assign the elements in the tuple to multiple variables the process of. This operation can be easily accomplished using tuples created with the tuple() function.
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.

  1. Tuple as function return value
    Using the tuple() function, you can combine some values ​​into a tuple and use them as the return value of the function.
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn