"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How do I create multiple variables from a list of strings in Python?

How do I create multiple variables from a list of strings in Python?

Published on 2024-11-16
Browse:918

How do I create multiple variables from a list of strings in Python?

How can I create multiple variables from a list of strings? [duplicate]

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3