Say I have a python list with 5 elements; list = ['a','b','c','d','e']. And I want to change it into 5 different strings so that each element is its own string, for example, str1 = a str2 = b str3 = c str4 = d str5 = e How would that be done? Note: I would want it to be done autonomously if possible as the number of elements in a list is variable according to the data that is input at the beginning of the original code.
-
Why can't you use `str1=mylist[0]`, `str2=mylist[1]`, etc. ? – Aziz Apr 17 '22 at 15:22
-
You may want to do list unpacking: `a, b, c, d, e = ['a','b','c','d','e']` – mara004 Apr 17 '22 at 15:24
-
I'd be curious to know when `str1`, `str2`, etc. is preferable to `s[1]` , `s[2]`. It sounds like you are about to make a mistake you will later regret. If you do this "autonomously", how will you know if you can safely access `str87`? – Mark Apr 17 '22 at 15:28
-
Check [generating variable names on fly in python](https://stackoverflow.com/questions/4010840/generating-variable-names-on-fly-in-python). Maybe just give a more meaningful name to your list (for instance `str` and there you have your variables `str[0], str[1]`, etc. – user2314737 Apr 17 '22 at 15:32
1 Answers
list_ = ['a','b','c','d','e']
You can use something called list unpacking, that you can do this way:
a, b, c, d, e = list_
As @Mark told you in the comments...
I'd be curious to know when
str1,str2, etc. is preferable tos[1],s[2]. It sounds like you are about to make a mistake you will later regret.
...you should avoid this approach.
If you don't know the lenght, you should read this, which suggests you to use the * star operator...
first, second, *others, third, fourth = names
...until you have the whole list unpacked.
Since you don't want to write an hell of if/elif/else over the lenght, I would suggest you to use exec to create variables on fly, even if (like Mark said) it's a bad idea.
I really want you to get that this is a bad idea, but you can use unpacking for useful scopes, in this case I would suggest you to read this, this and the respective PEP.
- 3,873
- 4
- 8
- 28