Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How do I convert between tuples and lists in Python?
Python provides simple built-in functions to convert between tuples and lists. Use list() to convert a tuple to a list, and tuple() to convert a list to a tuple.
Converting Tuple to List
To convert a tuple to a list, use the list() function with the tuple as a parameter.
Example with Integer Elements
# Creating a Tuple
mytuple = (20, 40, 60, 80, 100)
# Displaying the Tuple
print("Tuple =", mytuple)
print("Tuple Length =", len(mytuple))
# Tuple to list
mylist = list(mytuple)
# Display the list
print("List =", mylist)
print("Type =", type(mylist))
Tuple = (20, 40, 60, 80, 100) Tuple Length = 5 List = [20, 40, 60, 80, 100] Type = <class 'list'>
Example with String Elements
# Creating a Tuple with strings
mytuple = ("Jacob", "Harry", "Mark", "Anthony")
# Displaying the Tuple
print("Tuple =", mytuple)
print("Tuple Length =", len(mytuple))
# Tuple to list
mylist = list(mytuple)
# Display the list
print("List =", mylist)
print("Type =", type(mylist))
Tuple = ('Jacob', 'Harry', 'Mark', 'Anthony')
Tuple Length = 4
List = ['Jacob', 'Harry', 'Mark', 'Anthony']
Type = <class 'list'>
Converting List to Tuple
To convert a list to a tuple, use the tuple() function with the list as a parameter.
Example
# Creating a List
mylist = ["Jacob", "Harry", "Mark", "Anthony"]
# Displaying the List
print("List =", mylist)
# Convert List to Tuple
mytuple = tuple(mylist)
print("Tuple =", mytuple)
print("Type =", type(mytuple))
List = ['Jacob', 'Harry', 'Mark', 'Anthony']
Tuple = ('Jacob', 'Harry', 'Mark', 'Anthony')
Type = <class 'tuple'>
Key Differences
| Feature | Tuple | List |
|---|---|---|
| Mutability | Immutable | Mutable |
| Syntax | (1, 2, 3) | [1, 2, 3] |
| Performance | Faster | Slower |
Conclusion
Use list() to convert tuples to lists when you need mutable data. Use tuple() to convert lists to tuples when you need immutable, hashable data structures.
Advertisements
