Home >Backend Development >Python Tutorial >How to Create Multiple Variables from a List of Strings in Python?
Creating Multiple Variables from a List of Strings in Python
In Python, you may encounter situations where you need to create multiple variables from a list of strings. For instance, consider you have a list:
names = ['apple', 'orange', 'banana']
Your goal is to create separate lists for each element, named after the corresponding string:
apple = [] orange = [] banana = []
Solution
To achieve this, you can employ a dictionary:
fruits = {k: [] for k in names}
This creates a dictionary where keys are strings from the 'names' list, and values are empty lists.
Usage
To access each list, you can use the dictionary key:
fruits['apple'] # Returns an empty list for 'apple' fruits['orange'] # Returns an empty list for 'orange' fruits['banana'] # Returns an empty list for 'banana'
Benefits of Using a Dictionary
While creating separate variables for each element may seem logical, using a dictionary offers several benefits:
The above is the detailed content of How to Create Multiple Variables from a List of Strings in Python?. For more information, please follow other related articles on the PHP Chinese website!