Consider a list I want to parse using a for
:
friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]
for i in friends:
print i
will return :
"Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"
However, if I want to put it to a (str) variable, like :
friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]
for i in friends:
var=i
first I have to declare another var
variable, which is silly but whatever.
then,
print var
will return the last element of the list, which is "Paris", because the variable is overwritten for each iteration right.
So my question is : how can I assign the output of my loop "i", for each iteration, to a variable in Python ?
Sorry for the sillyness of this question but this is a concept I can't seem to figure out clearly.
If I understand well, you'd like to dynamically create variables. Here it is.
from collections import OrderedDict
friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]
d = OrderedDict()
for idx, value in enumerate(friends):
key = 'var' + str(idx)
d[key] = value
print(d)
# Output
OrderedDict([('var0', 'Joe'), ('var1', 'Zoe'), ('var2', 'Brad'), ('var3', 'Angelina'), ('var4', 'Zuki'), ('var5', 'Thandi'), ('var6', 'Paris')])
I also have this question, this is how I managed to solve it somewhat:
friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]
new_friends = ' '.join([x for x in friends])
print(new_friends)
Will return:
Joe Zoe Brad Angelina Zuki Thandi Paris
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