I have a list of strings such as:
names = ['apple','orange','banana']
And I would like to create a list for each element in the list, that would be named exactly as the string:
apple = []
orange = []
banana = []
How can I do that in Python?
Creating a list of same values by List Comprehension with range() This is an another way to create a list of same value using range() i.e. In this list comprehension, for loop will iterate over the range object 20 times and in each iteration it will add 'Hi' in the list. So, list will coatain 20 'Hi' elements i.e.
To create a list of strings, first use square brackets [ and ] to create a list. Then place the list items inside the brackets separated by commas. Remember that strings must be surrounded by quotes.
List<string> lines = new List<string> (File.ReadAllLines ("your file")); lines.Add ("My new line!"); Note the static helper method on the System.IO.File static class. I can't remember off-hand, but I think it returns a string array, which you can feed into the constructor of the list. foreach (string line in lines) { Console.WriteLine (line); }
You can also create a new list with only one string in it and add it to the current list: To print a whole list of strings in one line, you can simply call the built-in print function, giving the list as an argument:
Create unique list from column with VBA In Excel, you also can use VBA code to create a unique list from a given column. 1. Press Alt + F11 to show Microsoft Visual Basic for Applications window, and click Insert > Module, then copy and paste below VBA to the new Module window.
You would do this by creating a dict
:
fruits = {k:[] for k in names}
Then access each by (for eg:) fruits['apple']
- you do not want to go down the road of separate variables!
Always use Jon Clements' answer.
globals()
returns the dictionary backing the global namespace, at which point you can treat it like any other dictionary. You should not do this. It leads to pollution of the namespace, can override existing variables, and makes it more difficult to debug issues resulting from this.
for name in names:
globals().setdefault(name, [])
apple.append('red')
print(apple) # prints ['red']
You would have to know beforehand that the list contained 'apple' in order to refer to the variable 'apple' later on, at which point you could have defined the variable normally. So this is not useful in practice. Given that Jon's answer also produces a dictionary, there's no upside to using globals
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With