1

I have a several lists with items inside:

a = [1,2,3,4]
b = [5,6,7,8]
c = [9,10,11,12]

Also I have another list with names of lists saved as strings:

names = ['a', 'b', 'c']

I want to print items from those lists (a,b,c) using name from list names in a loop (smt. like this):

for i in names:
    print(i)

And the output will be:

'a'
'b'
'c'

But I want to get:

[1,2,3,4]
[5,6,7,8]
[9,10,11,12]

I need to convert strings to variables in a loop somehow.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
AirMax
  • 23
  • 4

2 Answers2

0

You can create dict of list with 'a','b','c' as keys as follows

d = {}
d['a'] = [1,2,3,4]
d['b'] = [5,6,7,8]
d['c'] = [9,10,11,12]

names = ['a', 'b', 'c']
for i in names:
    print(d[i])
shreyas
  • 2,510
  • 4
  • 19
  • 20
-2

try below code:

a = [1,2,3,4]
b = [5,6,7,8]
c = [9,10,11,12]
names = ['a', 'b', 'c']
for i in names:
    locals()[i]
jimidime
  • 542
  • 3
  • 5
  • Thank you. It works – AirMax Nov 07 '17 at 12:28
  • 1
    There's a notable difference between "it works" and "you should actually do this". See [Why is using `eval` bad practice](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice). – miradulo Nov 07 '17 at 12:29
  • Please don't use `eval`, especially not when there are safer alternatives like `locals()` (or a dict). Newbies reading `eval` answers get the impression that it's ok and safe and normal to use eval, none of which is true. – Aran-Fey Nov 07 '17 at 12:31
  • ok, thank you. Will read why eval is a bad practice. – AirMax Nov 07 '17 at 12:34
  • Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) its long-term value by showing *why* this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made and the drawbacks of this approach. – Toby Speight Nov 07 '17 at 12:45