Home > Article > Backend Development > How do I create multiple variables from a list of strings in Python?
Many programming scenarios require us to manipulate multiple objects or variables simultaneously. A common challenge is creating multiple variables from a list of strings, where each variable's name matches the corresponding element in the list.
In Python, you can accomplish this using a dictionary comprehension:
names = ['apple', 'orange', 'banana'] fruits = {k: [] for k in names}
This code snippet iterates through the names list and generates a new dictionary called fruits. For each string in the list (e.g., 'apple'), a new key is created in the dictionary, and its associated value is initialized to an empty list.
Once the dictionary is created, you can access each variable using the corresponding string key. For instance, fruits['apple'] would return an empty list.
Alternatively, you could use a for loop to create separate variables for each string element:
for name in names: globals()[name] = []
However, this approach is discouraged as it creates global variables, which can introduce potential issues in complex programs. The dictionary comprehension method is preferred for its flexibility and localized scope.
The above is the detailed content of How do I create multiple variables from a list of strings in Python?. For more information, please follow other related articles on the PHP Chinese website!