0

I have 3 list

list_a =['hii','hello','hai']
list_b = ['john','david']

main_list = ['list_a','list_b']

how can i iterate items in list_a and list_b using items in main_list ? is it possible to do in a single line.

Desired output

hii
hello
hai
john
david
Aniiya0978
  • 274
  • 1
  • 9
  • nice question, I'm going to answer you. – FLAK-ZOSO Sep 13 '21 at 13:36
  • 2
    So `main_list` is a list of strings of the names of the other lists, not the actual lists themselves? – Peter Wood Sep 13 '21 at 13:38
  • 1
    This sort of question has multiple answers (the first of which is really ["you have an XY problem"](https://meta.stackexchange.com/q/66377/322040)), but the various answers on [the duplicate](https://stackoverflow.com/q/1373164/364696) cover all the options. In your case, using `globals()` or `locals()` would get you the `dict` that would let you look up the string names you've got. – ShadowRanger Sep 13 '21 at 13:39
  • @Aniiya0978, the post has been closed (because there was more than a question in there). You can find your answer in https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables – FLAK-ZOSO Sep 13 '21 at 13:42
  • Gee, not so many of those answers in the linked post answer this question. You probably want to use the `eval()` builtin to reference a variable named in a string. E.g. `for list_ in main_list: for item in eval(list_): print(item)`. – Graham501617 Sep 13 '21 at 13:47
  • @Graham501617: `eval` is a suboptimal solution in most cases given it has to fire up the Python compiler (and might do more than just look up names); `for item in globals()[list_]:` (sub `locals()` for `globals()` if the variables are at function scope) would do the trick without that issue (it's the third-ranked answer on the dupe at time of posting). – ShadowRanger Sep 13 '21 at 15:01

1 Answers1

0

I believe the most "pythonic" way would be to use itertools.chain:

list_a =['hii','hello','hai']
list_b = ['john','david']
for name in itertools.chain(list_a, list_b):
    print(name)

The cool thing about this is that it works for any iterables, not just lists. So you could combine lists, sets, an iterable of dictionary keys, a custom generator function, etc. all into one iterable.

You can also pass a list of iterables instead of variadic arguments by using itertools.chain.from_iterable:

list_a = ['hii', 'hello', 'hai']
list_b = ['john', 'david']
main_list = [list_a, list_b]
for name in itertools.chain.from_iterable(main_list):
    print(name)

And if you really need the elements of main_list to be strings (protip: you probably don't):

main_list = ['list_a', 'list_b']
for name in itertools.chain.from_iterable(globals().get(list_name, []) for list_name in main_list):
    ...
0x5453
  • 12,753
  • 1
  • 32
  • 61