0

Suppose too many lists:

fred = ['one', 'two', 'three']
jim = [1, 2, 3]
# and many others

I want this ['one', 'two', 'three', 1, 2, 3, ......] and tried as following codes

dir()
output: ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'fred', 'jim']
multiple_list_names = [ e for e in dir() if "__" not in e]
output:['fred', 'jim']

then,

new_list = []
for name in multiple_list_names:
    for elem in eval(name):
        new_list.append(elem)
print(new_list)
output:['one', 'two', 'three', 1, 2, 3,]

How to do it smarter?

cs95
  • 379,657
  • 97
  • 704
  • 746
  • 1
    Related: https://stackoverflow.com/questions/45666957/how-to-draw-elements-out-of-multiple-list-to-create-an-uncompanied-one/45667064#45667064 See my answer with `globals`. – cs95 Aug 14 '17 at 06:07
  • 1
    `new_list = [*fred, *jim]`. – Christian Dean Aug 14 '17 at 06:08
  • @cᴏʟᴅsᴘᴇᴇᴅ Found a good dupe. Well, maybe. The OP seems to be asking about concatenation, but then starts doing stuff with global variables and `eval`. – Christian Dean Aug 14 '17 at 06:09
  • @ChristianDean I'm second guessing myself. I think OP's intent is to have this work for an arbitrary number of unknown lists. if not confirmed, this will remain shut. – cs95 Aug 14 '17 at 06:10
  • @cᴏʟᴅsᴘᴇᴇᴅ Hmm, yes. I see your point. If that's the case the OP should probably be advised to use a list of lists. – Christian Dean Aug 14 '17 at 06:15
  • yes , but about concatenation without copying the variable names already typed in.@ChristianDean –  Aug 14 '17 at 06:21

0 Answers0