Python implements conversion of tuple and list
In Python, it is easy to use built-in functions to translatetuple
(tuple) convert tolist
(list), orlist
Convert totuple
。
The following are the specific implementation methods:
Convert tuple to list
Use built-inlist()
Functions can convert onetuple
Convert 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 onelist
Convert 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 totuple
andlist
Convert 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
-
Immutability:
tuple
is immutable (i.e., once created, its content cannot be modified), andlist
is variable (ie, its contents can be modified). -
performance:because
tuple
is immutable, so in some cases, usetuple
Probably more than usinglist
More efficient, especially when frequent readings are required but no data modification is required.
Through the above method, it can be easily implemented in Pythontuple
andlist
Conversion between.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.