Home  >  Article  >  Backend Development  >  How to Create Multiple Variables from a List of Strings in Python?

How to Create Multiple Variables from a List of Strings in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-11-17 10:48:03838browse

How to Create Multiple Variables from a List of Strings in Python?

Creating Multiple Variables from a List of Strings

Given a list of strings like:

names = ['apple', 'orange', 'banana']

You may want to create a list associated with each string, named exactly like the string:

apple = []
orange = []
banana = []

How to Achieve This in Python

To accomplish this task, you can employ the following approach:

Create a dictionary using list comprehension:

fruits = {k:[] for k in names}

This creates a dictionary where each key corresponds to a string in names, and each value is an empty list.

Access the list associated with a particular string using the dictionary key:

fruits['apple']

This returns the empty list associated with the string 'apple'.

Note:

It's generally better to use a dictionary rather than creating separate variables for each string, as it provides flexibility and easy access to the data associated with each string.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn