Neel
Neel

Reputation: 643

Effeciently extend n number of lists together

Say you have an infinite number of python lists.

How would you efficiently extend all of them together without manually writing out the extend function?

For instance,

l1 = [1, 2, 3, ..., n]
l2 = [1, 2, 3, ..., n]
.
.
.
ln = [1, 2, 3, ..., n]

# Not this
l1.extend(l2)
l1.extend(l3)
.
.
.
l1.extend(ln)

Thanks!

Upvotes: 2

Views: 84

Answers (4)

qaiser
qaiser

Reputation: 2868

l1 = [1,2,3,4,5]
l2 = [5,6,7,8,9]
l3  = [10,11,12,13]
y = [l2,l3]

[l1.extend(x) for x in y] 
print(l1)

Out[33]:
[1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10, 11, 12, 13]

updated

 y = ['l{}'.format(y) for y in range(0,100)] # to get all 100 list, l1,l2,l3...l100
 [l1.extend(eval(x)) for x in y]

Upvotes: 0

neutrino_logic
neutrino_logic

Reputation: 1299

You'd need something to generate your infinite series of lists, like:

def feeder(n):
    while True:
        yield[x for x in range(n)]

and then a function to link one to the next forever:

def extender(n):
    a = feeder(n)
    ln = []
    while True:
        ln += next(a)

Then, >>> extender(100) fills up memory fairly quickly. [Edit change lists as per question]

Upvotes: 0

oppressionslayer
oppressionslayer

Reputation: 7204

You can add them together [1,2,3] + [3,4,5], that's another way

If you have a bunch of variables like l1,l2,l3,l4,l5, you can do something like this:

for x in range (1,5): 
   new_list = new_list + eval('l' + str(x)) 

which would add lists together that aren't grouped into a list of lists.

Here's one that handles an inconsistent format without errors:

l1=[1,3]
l2=[4,5]
l3=[5,6]
n1=[2,3]
n5=[4,7]


new_list=[]
letters = ['l','n']
for items in letters:
    for x in range(0,6):
       try:
          new_list = new_list + eval(items + str(x))
       except: 
           continue

Upvotes: 0

Jab
Jab

Reputation: 27485

itertools.chain

list(chain(l1, l2, ..., ln)
#[1,2,3, ..., ln[n]]

Upvotes: 3

Related Questions