Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign the result of a loop to a variable in Python

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.

like image 358
Nahid O. Avatar asked Jun 20 '16 08:06

Nahid O.


2 Answers

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')])
like image 55
SparkAndShine Avatar answered Sep 28 '22 05:09

SparkAndShine


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
like image 21
e71az Avatar answered Sep 28 '22 04:09

e71az