0

I wanted a separate list of 2 and 3 from an input list. for 1 1 2 2 3 3 4 4 as input I want to have [1,1,4,4] and [2,2,3,3] as outputs. But I am getting [1,1,2,3,4,4] and [2,3] instead. What is the problem with my code?

n = [int(x) for x in input().split()]
print(n)
K = []
for i in n:
    if i == 2 or i == 3:
        K.append(i)
        n.remove(i)
print(K)
print(n)
Dirk Horsten
  • 3,753
  • 4
  • 20
  • 37

2 Answers2

1

You try this using list comprehension.

my_list=[1,1,2,2,3,3,4,4]
ones,twos=[[i for i in my_list if i not in {2,3}],[i for i in my_list if i in {2,3}]]
ones
# [1, 1, 4, 4]
twos
# [2, 2, 3, 3]

Or using defaultdict

from collections import defaultdict
my_list=[1,1,2,2,3,3,4,4]
out=defaultdict(list)
for i in my_list:
    k='2' if i in {2,3} else '1' # you can also do `k=i in {2,3}` but keys will be `True` and `False`
    new[k].append(i)
new
# defaultdict(list, {'1': [1, 1, 4, 4], '2': [2, 2, 3, 3]})

You can also do k=i in {2,3} but keys will be True and False instead of k='2' if i in {2,3} else '1'

If you use k=i in {2,3} new will look like this:

defaultdict(list, {False: [1, 1, 4, 4], True: [2, 2, 3, 3]})
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
1

The problem is that you are mutating n at the same time that you're iterating over it. Whenever you call n.remove(), on the next iteration, python moves from list position 3 to list position 4, but you just turned list position five into list position four, so the original item in position four never gets checked.

If you simply use the python copy module to iterate over a copy of n, and then mutate n aside from iterating over it, your problem disappears.

from copy import copy

inp = '1 1 2 2 3 3 4 4'
n = [int(x) for x in inp.split()]
copy_of_n = copy(n)
K = []
for i in copy_of_n:
    if i == 2 or i == 3:
        K.append(i)
        n.remove(i)

print(K, '\n', n)

Additionally, you can accomplish this more efficiently with list comprehensions:

inp = '1 1 2 2 3 3 4 4'
l_23 = [num for num in inp.split() if num is '2' or num is '3']
l_14 = [num for num in inp.split() if num is '1' or num is '4']

print(l_23)
print(l_14)
jdevries3133
  • 135
  • 1
  • 6