9

In python we can add lists to each other with the extend() method but it adds the second list at the end of the first list.

lst1 = [1, 4, 5]
lst2 = [2, 3]

lst1.extend(lst2)

Output:
[1, 4, 5, 2, 3]

How would I add the second list to be apart of the 1st element? Such that the result is this;

[1, 2, 3, 4, 5 ]

I've tried using lst1.insert(1, *lst2) and got an error;

TypeError: insert expected 2 arguments, got 3
Cleo
  • 25
  • 4

3 Answers3

13

For those who don't like reading comments:

lst1 = [1, 4, 5]
lst2 = [2, 3]

lst1[1:1] = lst2
print(lst1)

Output:

[1, 2, 3, 4, 5]
Jamiu S.
  • 5,257
  • 5
  • 12
  • 34
-1

If your only goal is to get the list sorted correctly, then you use .extend() and .sort() afterwards.

Mou
  • 1
  • 1
-2

You can solve your problem in two steps:

  • Insert the list into the other list
  • Flatten the result

Code:

from collections.abc import Iterable

# https://stackoverflow.com/questions/2158395/flatten-an-irregular-arbitrarily-nested-list-of-lists
def flatten(xs):
    for x in xs:
        if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
            yield from flatten(x)
        else:
            yield x

xs = [1,4,5]
ys = [2,3]
xs.insert(1, ys)
print("intermediate result", xs)
xs = flatten(xs)
print(xs)
Caridorc
  • 6,222
  • 2
  • 31
  • 46
  • 2
    You can't iterate over integers. This answer would raise a `TypeError`. – Jasmijn Jan 15 '23 at 12:49
  • @Jasmijn Uh thanks a lot for the bug report, I updated the flatten function to work also in this case – Caridorc Jan 15 '23 at 13:29
  • But without calling `flatten(xs)` in a `list` function it will generate an object. So you will have to convert the iterator object to a list like. `xs = list(flatten(xs))` – Jamiu S. Jan 15 '23 at 13:44
  • @JamiuShaibu It depends on your situation, sometimes using a generator will be more efficient – Caridorc Jan 15 '23 at 14:03