What Is the Syntax to Insert One List into Another List in Python

What is the syntax to insert one list into another list in python?

Do you mean append?

>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x.append(y)
>>> x
[1, 2, 3, [4, 5, 6]]

Or merge?

>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x + y
[1, 2, 3, 4, 5, 6]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 5, 6]

How to insert the contents of one list into another

You can do the following using the slice syntax on the left hand side of an assignment:

>>> array = ['the', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']
>>> array[1:1] = ['quick', 'brown']
>>> array
['the', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']

That's about as Pythonic as it gets!

Inserting the elements of a list to the middle of another list

a = ['****', '****']
b = ['abc', 'efg']
mid_index = len(a)//2 # Integer result for a division

result = a[:mid_index] + b + a[mid_index:]

If you want to assign the result to a directly, You can also simply:

a[mid_index:mid_index] = b

Insert list values into another list (python)

Your posted code very explicitly adds every letter to each list. Instead, you want to add only the corresponding letter. You need one loop index for both lists, not nested loops.

for i in range(len(List1)):
List1[i].append(List2[i])

How to append a list to another list in a python for loop when each element of the existing list is being changed inside the for loop?

When you append r1 twice to r2 it essentially makes r2 a list of [r1, r1] not the contents of r1 when it was appended, so when r1 is changed before the second append, the first element in r2 which is a reference to r1 is also changed.

One solution is to not use r1 at all and just append the contents directly:

r2 = []
r_1 = {'G':32,'H':3}
for i in r_1:
r2.append([i, i+"I"])
print(r2)

A second solution is to append a copy of r1 to avoid the two elements having the same reference:

r2 = []
r_1 = {'G':32,'H':3}
r1 = [None, None]
for i in r_1:
r1[0] = i
r1[1] = i + "I"
r2.append(r1.copy())
print(r2)

How can I insert elements of one list into another list in the same order?

It is generally not recommended to use "side effects" within a list comprehension nor to use them in place of a for loop. You can insert a list into another list using simple subscripts however:

more_fruit = ["pear", "pineapple", "coconut"]
my_list = ["apple", "orange", "banana", "peach"]

my_list[0:0] = more_fruit

output:

print(my_list)

# ['pear', 'pineapple', 'coconut', 'apple', 'orange', 'banana', 'peach']

note: a subscript is a reference to some elements in the list, either a single element or a range of elements. In this case, we are replacing a range of elements containing zero elements starting at position 0.

How to append all elements of one list to another one?

You could use addition:

>>> a=[5, 'str1']
>>> b=[8, 'str2'] + a
>>> b
[8, 'str2', 5, 'str1']


Related Topics



Leave a reply



Submit