I have the following string: List =[[1], ['apple', 2], [3], [4], [5], [6], [7]]
How can I extract the sub-lists as following: s1 = [1] s2 = ['apple', 2] ... s7 = [7] ?
Thank you for your help.
I have the following string: List =[[1], ['apple', 2], [3], [4], [5], [6], [7]]
How can I extract the sub-lists as following: s1 = [1] s2 = ['apple', 2] ... s7 = [7] ?
Thank you for your help.
You have to use unpacking
>>> L = [[1], ['apple', 2], [3], [4], [5], [6], [7]]
>>> s1, s2, s3, s4, s5, s6, s7 = L
>>> s1
[1]
>>> s2
['apple', 2]
>>> s7
[7]
If you want to create 7 variables named s1 through s7, the most straightforward way is to do direct assignment.
s1 = List[0]
S2 = List[1]
...
S7 = List[6]
A second approach is to put all the assignments on one line and let python unpack the list, as described by @Lafada.
A third approach is to use exec, which may be more scalable for larger numbers of variables, although the value of all these separate names instead of the original list is not clear to me.
L = [[1], ['apple', 2], [3], [4], [5], [6], [7]]
for i in xrange(7):
exec("s%d = L[%d]" % ((i+1), i))
Update: Based on OP's comment, he is starting with a string. Each of these approaches can be used, after we first convert the string to a list using ast.literal_eval.
import ast
List = "[[1], ['apple', 2], [3], [4], [5], [6], [7]]"
L = ast.literal_eval(List)