1

I have this list and I want to sort the list. This is just a smaller example of what I want to do, but I get the same error. I dont understand why I can't make this work. I have tried using google to solve the problem but without luck.

lst = [3, 4, 5, 6]

if lst < 4:
    lst.pop()
    print(lst)

How can i do this it shows

TypeError:'<' not supported between instances of 'list' and 'in

1 Answers1

1

I think that your goal is to remove all elements in the list that are lesser than 4. You can use this simple list comprehension in order to achieve what you want:

lst = [3, 4, 5, 6]
lst = [elem for elem in lst if elem >= 4]
print(lst)

Output:

[4, 5, 6]
Sushil
  • 5,440
  • 1
  • 8
  • 26
  • what if i want to do it for >=4 and <=5 can i put both inside ? – Kristoffer Karlsen Oct 26 '20 at 08:13
  • Do u want both conditions (i.e >= 4 and <=5) to be satisfied? – Sushil Oct 26 '20 at 08:14
  • 1
    Try this: `lst = [elem for elem in lst if elem >= 4 and elem <= 5]` – Sushil Oct 26 '20 at 08:17
  • 1
    It works but is there a way i can put an id. on the elemets ? so that i get 4 has id 1 and 5 has id 2 from the original list :) ? – Kristoffer Karlsen Oct 26 '20 at 08:26
  • Do you want to create a new list with the ids? – Sushil Oct 26 '20 at 08:28
  • the list i am working on has 11000 elements and when i used your code on it to reduce it, i want to have the ability to se what id it had in the original list. if that makes sence – Kristoffer Karlsen Oct 26 '20 at 08:31
  • 1
    What about this: `lst = [[index,elem] for index,elem in enumerate(lst) if elem >= 4 and elem <= 5]` Output: `[[1, 4], [2, 5]]` (the first num is the id, the second num is the number) – Sushil Oct 26 '20 at 08:41
  • What if i had 2 list that i sorted like that and wanted and to make a new list that would only contain the same index as the 2 list `lst = [[1,2], [4,5] , [5,2]] lst2 = [[3,4], [4,2], [6,3]]` and then i want a list where the index (first nr) is the same `lst_total =[4, 5, 2]` or `lst_total =[4]` – Kristoffer Karlsen Oct 26 '20 at 10:12
  • Can u rephrase ur question? – Sushil Oct 26 '20 at 11:04
  • if there are 2 list with the same index is there a way that i can make a new list with all the index that goes agien for the 2 list ? – Kristoffer Karlsen Oct 26 '20 at 12:10
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/223663/discussion-between-sushil-and-kristoffer-karlsen). – Sushil Oct 27 '20 at 03:20