Combine two lists and sort them

Question:

Lets say I have two lists. I want to append list2 into list1 and then sort and add a new element at a specific index.
I keep getting an error message saying:

TypeError: ‘<‘ not supported between instances of ‘list’ and ‘int’

This is what I have tried:

list1 = [11, -21, 23, 45, 66, -93, -21]
list2 = [15, 67, -40, -21, 10]
list1.append(list2)
list1.insert(4, 50)
print(list1.sort())
Asked By: Will

||

Answers:

Instead of using list1.append(list2), use this: list1=list1+list2.
You can also use list1.extend(list2).

Answered By: Anuj Kumar

Don’t use append, use extend. You are adding the second list as an element on the first list

>>> list1 = [11, -21, 23, 45, 66, -93, -21]
>>> list2 = [15, 67, -40, -21, 10]
>>> list1.append(list2)
>>> list1
[11, -21, 23, 45, 66, -93, -21, [15, 67, -40, -21, 10]]

Also, sort doesn’t return a list. It returns None.

>>> list1 = [11, -21, 23, 45, 66, -93, -21]
>>> list2 = [15, 67, -40, -21, 10]
>>> list1.extend(list2)
>>> list1
[11, -21, 23, 45, 66, -93, -21, 15, 67, -40, -21, 10]
>>> list1.insert(4, 50)
>>> list1
[11, -21, 23, 45, 50, 66, -93, -21, 15, 67, -40, -21, 10]
>>> list1.sort()
>>> list1
[-93, -40, -21, -21, -21, 10, 11, 15, 23, 45, 50, 66, 67]
>>>
Answered By: Gabriel Flores

You can combine two lists using the + operator:

my_list1 = [1, 2]
my_list2 = [3, 4]
combinedList = my_list1 + my_list2

To insert a new element, Just use .insert (with index and element)

combinedList.insert(0, 0)

Remeber that the Index is 0 based!

Answered By: Felix Asenbauer

Use sorted() if you want to print sorted list:

list1 = [11, -21, 23, 45, 66, -93, -21]
list2 = [15, 67, -40, -21, 10]
list1.insert(4, 50)
print(sorted(list1 + list2))

# [-93, -40, -21, -21, -21, 10, 11, 15, 23, 45, 50, 66, 67]
Answered By: user19584174
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.