SoFunction
Updated on 2025-04-14

Python implements the conversion method of tuple and list

Python implements conversion of tuple and list

In Python, it is easy to use built-in functions to translatetuple(tuple) convert tolist(list), orlistConvert totuple

The following are the specific implementation methods:

Convert tuple to list

Use built-inlist()Functions can convert onetupleConvert to onelist

# Define a tuplemy_tuple = (1, 2, 3, 4)

# Convert tuples to listmy_list = list(my_tuple)

print(my_list)  # Output: [1, 2, 3, 4]

Convert list to tuple

Use built-intuple()Functions can convert onelistConvert to onetuple

# Define a listmy_list = [1, 2, 3, 4]

# Convert list to tuplemy_tuple = tuple(my_list)

print(my_tuple)  # Output: (1, 2, 3, 4)

Sample code

Here is a complete sample code showing how totupleandlistConvert each other:

# Define a tupletuple_example = (1, 2, 3, 4)

# Convert tuples to listlist_from_tuple = list(tuple_example)
print("List from tuple:", list_from_tuple)

# Define a listlist_example = [5, 6, 7, 8]

# Convert list to tupletuple_from_list = tuple(list_example)
print("Tuple from list:", tuple_from_list)

Run the above code and the output will be:

List from tuple: [1, 2, 3, 4]
Tuple from list: (5, 6, 7, 8)

Things to note

  1. Immutabilitytupleis immutable (i.e., once created, its content cannot be modified), andlistis variable (ie, its contents can be modified).
  2. performance:becausetupleis immutable, so in some cases, usetupleProbably more than usinglistMore efficient, especially when frequent readings are required but no data modification is required.

Through the above method, it can be easily implemented in PythontupleandlistConversion between.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.