0

How to assemble the objects in a list and assign them into a variable in python?

I know how to print them, but I can't assign them in to a variable.

4th Nov 2019, 4:55 PM
Ishmam
Ishmam - avatar
6 Respostas
+ 3
is it something like this you want to do? res = '' lst=["me", "you", "them"] for i in lst: res += i + ' ' print(res) # output: 'me you them' # as already said, print can not assign any values to a variable, but you can do it like shown above
4th Nov 2019, 8:05 PM
Lothar
Lothar - avatar
+ 2
Since you question is unclear, I'm just going to answer it the way I understood it: First method: L = ['cat', 'dog', 'lion'] cat, dog, lion = L Second method: L = [i for i in range(100)] for i in L: eval(f'a{i} = {i}') The second method will dynamically assign variables, for example: a15 is equal to 15 a42 is equal to 42 Since you know to print them, I assume you know you can assign them using their index, like: a = L[2]
4th Nov 2019, 5:09 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 2
🔥Iƒαянαn🔥 🇧 🇩 what do you want to name the variable is what I'm asking for. If what you want is to assign the members of the list separated by a blank space, then you can simply use the join method: string = " ".join(lst)
4th Nov 2019, 5:41 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 2
The print() method doesn't return any value so you can't "assign the print statement to a variable" as you say. If you say a = print(*[i for i in lst]) a still only has the value None, even though the list gets printed. The only thing I can suggest (if I understand what you want) is to do a = "print(*[i for i in lst])" and, to call it, do exec(a), though I don't understand why you want to do this exactly. Although I think that Aymane Boukrouh [Inactive] 's answers covered all of this anyway.
4th Nov 2019, 7:29 PM
Russ
Russ - avatar
+ 2
Thanks guys. 😄 I got more than one answer.
5th Nov 2019, 2:52 AM
Ishmam
Ishmam - avatar
0
Aymane Boukrouh [Inactive] Ok, I am clearing out the question. For example: lst=["me", "you", "them"] for i in lst: print(i,end=" ") # this will print "me you them". # but I want to assign the print statement into a variable.
4th Nov 2019, 5:21 PM
Ishmam
Ishmam - avatar