Home > Net >  Combine two lists and sort them
Combine two lists and sort them

Time:10-05

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())

Thank you in advance for any and all help!

CodePudding user response:

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]
>>>

CodePudding user response:

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

CodePudding user response:

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]

CodePudding user response:

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!

  • Related