Home > Enterprise >  Appending many lists into a bigger list, and changing their sequence to fit the bigger list sequence
Appending many lists into a bigger list, and changing their sequence to fit the bigger list sequence

Time:06-09

I am doing a big O.O.P using python, I have a problem that I can not append more than two lists into one list.

This simple question might solve the problem:

I have three lists first ,second and third I want to append the three lists in bigger list and make second list 3 times, and the bigger list will have one new sequence of elemments.

bigger = []
first = [1,2,3,4]
for l in first:
    bigger.append(l)
second = [1,2,3,4,5]
for m in second:
    for i in range(3):
        bigger.append(m i)
third = [1,2,3]
for n in third:
    bigger.append(n)
print(bigger)

The output:

[1, 2, 3, 4, 1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 7, 1, 2, 3]

The desired output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]

I hope that you can follow me!

CodePudding user response:

I'm not sure of what you really want. To get the desired output, it is enough to do:

list(range(1, 23))

Otherwise, to build the bigger list with the procedure that you described, this should work:

bigger = [*first, *(second * 3), *third]

The second * 3 replicates three times the second list. The * in front of each list unpacks the values and puts them together into the bigger list.

CodePudding user response:

You just need to store the last element in bigger so far and add it to the elements in second and third as you append them. Also, the order of the loops are wrong when appending elements in second; the inner loop should be over second.

Also you mentioned you want to append to bigger element by element but lists have extend method that can extend bigger by another list.

bigger = []
first = [1,2,3,4]
for l in first:
    bigger.append(l)
second = [1,2,3,4,5]
for i in range(3):
    # track the last element
    last = bigger[-1]
    for m in second:
        # add the last here
        bigger.append(m last)
third = [1,2,3]
# track the last
last = bigger[-1]
for n in third:
    # add the last here
    bigger.append(n last)
print(bigger)
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
  • Related