-2

Below is a simple example. What I want is to create a new list that contain the values [0,1,2,3,4] by merging list1 and list 2 together. But the code below doesn't work and I am not really sure how I should solve it.

list1 = [3]
list2 = [i for i in range(3)]
newlist = list1.append(list2)
MathiasRa
  • 825
  • 2
  • 12
  • 24

2 Answers2

0

list.append(b) doesn't return a new list containing the elements of list and b, but it will extend list by one element (the element b) and save the result in list itself.

To concatenate two lists, simply use the + operator. Your code would look like this:

list1 = [3] 
list2 = [i for i in range(3)]
newlist = list1 + list2
fecavy
  • 185
  • 2
  • 12
  • Hi this question is very much a duplicate. If you come across duplicate questions please flag them and mark them as duplicates. Answering them encourages further bad behavior – ford prefect May 29 '18 at 21:48
0

@MathiasRa, your code will not work as append() method doesn't return any list.

Previous answers are appreciated. So can directly get your merged list [0, 1, 2, 3] using the below line.

list1 = [3]
list2 = [i for i in range(3)]
newlist = sorted(list1 + list2)

print (newlist) # [0, 1, 2, 3]

» If you don't want updated list as return value

Use extend() method in place of append() as follows:

Note: In this case, you won't get anything returned like append(). The statement will update the calling list (list1) by appending all items of passing list (list2).

list1 = [3]
list2 = [i for i in range(3)]
list1.extend(list2)

print(list1) # [3, 0, 1, 2]
print(sorted(list1)) # [0, 1, 2, 3]
hygull
  • 8,464
  • 2
  • 43
  • 52