0

I'm just doing a simple python exercise that looks like this:

list1 = [47, 48, 49, 50, 51, 52, 53, 54]
list2 = []

for num in list1:
  if num >= 50:
    list1.remove(num)
    list2.append(num)

print(list1)
print(list2)

List 1 should only have numbers less than 50 and list 2 should have numbers greater than or equal to 50. However, the output says otherwise:

List1: [47, 48, 49, 51, 53]
List2: [50, 52, 54]

How can I fix this?

2 Answers2

0

This is not a good way doing it. you are removing items from list during iteration.

when you remove items from a list during a loop. it will effect the indexing of the list. that is why you see your code jumps through some of items.

it is easier to use list comprehensions:

list1 = [47, 48, 49, 50, 51, 52, 53, 54]


list2 = [i for i in list1 if i>=50]
list1 = [i for i in list1 if i<50]
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
0

You can also filter,

list1 = [47, 48, 49, 50, 51, 52, 53, 54]

list2 = filter(lambda x: x<50,  list1)   # print(list(list2))
list3 = filter(lambda x: x>=50, list1)   # print(list(list3))

Or use indexing:

import numpy as np 

l1 = np.array(list1)
list2 = l1[l1 <  50]
list3 = l1[l1 >= 50]
AboAmmar
  • 5,439
  • 2
  • 13
  • 24