1

I've a string represenation of list inside a list.

l=['[0, 1]', '[2, 3]']

and I need to convert it into the list

l=[[0, 1], [2, 3]]

but I don't know how. Till now to change a string to a list I had used the split mehod but it seems not useful here. Any idea? Thanks.

UlyssesJA
  • 121
  • 1
  • 4
  • If your strings are only ever representations of lists of ints, then you could use the `json` module. – quamrana Nov 29 '22 at 16:53
  • Do the answers to this [question](https://stackoverflow.com/questions/1894269/how-to-convert-string-representation-of-list-to-a-list) help at all? – quamrana Nov 29 '22 at 16:54
  • @quamrana OP *could* use the `json` module, but this runs the risk of conflating `json` with `ast`, which have two distinct purposes. `ast` is the better fit here, since they are trying to convert a string to a python object, rather than parse a json string – C.Nivs Nov 29 '22 at 17:00
  • 1
    @C.Nivs: Yes, I'm sure that `ast` can be used. Unfortunately I'm not familiar with that module and its not 100% clear where this data came from, so `json` *could* be useful. – quamrana Nov 29 '22 at 17:04
  • This question differnt..I request to open this question again...Applying `eval` directly or `json.load` deosn't solve the problem – Bhargav - Retarded Skills Nov 29 '22 at 17:20
  • @Bhargav: How is this question different? I'm quite happy with the selected duplicate. – quamrana Nov 29 '22 at 17:22
  • @quamrana Have you applied `eval` or `Json.load()` on this exaple? have you got outputs? it's not string representaion of list...it's string represenation of list inside a list – Bhargav - Retarded Skills Nov 29 '22 at 17:23
  • 1
    @Bhargav: This question is not that different. The answers in the duplicate use `ast` and `json`. Its easy to apply the same techniques to this question. One solution could be: `l = [json.loads(item) for item in l]` – quamrana Nov 29 '22 at 17:30
  • Yeah atlast we have to apply `ast` and ` json` before that we need to modify the input by converting entire list to string so that it will become string represenation of `sublist` then we have to apply `ast` or `json`. I hope OP looking for way to achieve this process. – Bhargav - Retarded Skills Nov 29 '22 at 17:33
  • ohh @quamrana it was a nice solution!!!!..But if we use ast it wont be possible directly I guess – Bhargav - Retarded Skills Nov 29 '22 at 17:35

0 Answers0