Search code examples
pythonlistconcatenation

Adding Lists together using Variable Name


Suppose we have have 100 lists called list_1, list_2, ..., list_100

If we want to combine these lists, how would we do this? Would something like this work:

for i in range(101):
    list_combined += list_{i}
print(list_combined)

Solution

  • If you absolutely must have 100 lists as specified in the question, you can do the following:

    list_combined = []
    for i in range(1, 101):
        list_combined += eval(f"list_{i}")
    print(list_combined)
    

    I strongly discourage this approach in favor of making a list of lists instead, but it will work.