1

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.

3
  • Hi. You say "lists to strings". Do you actually want the variables s1...s7 to have string values? Also, do you need actual variables? Do you have multiple lists of various sizes, or just the one list? Commented Feb 23, 2015 at 4:14
  • I am sorry, I have to correct my question. The original list (here List) is a string so s1=List[0] gives me '['. Actually I want to convert this string to 7 lists. Commented Feb 23, 2015 at 4:28
  • See the update to my answer. Commented Feb 23, 2015 at 4:33

4 Answers 4

4

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]
Sign up to request clarification or add additional context in comments.

1 Comment

I am sorry, I have to correct my question. The original list (here List) is a string so s1=List[0] gives me '['. Actually I want to convert this string to 7 lists.
3

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)

2 Comments

I am sorry, I have to correct my question. The original list (here List) is a string so s1=List[0] gives me '['. Actually I want to convert this string to 7 lists.
@PouyaKh please edit your question to clarify what you want
2

Simply you could try the below.

s = []
s[:7] = List

Comments

1

Try this code

List=[[1], ['apple', 2], [3], [4], [5], [6], [7]]

output=""
for list_index in range(len(List)):
    output+="s%s = %s "%(list_index,List[list_index])


print output

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.