0

I have a list that contains integer elements. I wanted to split the elements into 2 lists. One should contain single digits, another one should contain multi-digit elements. After adding the elements to another list I wanted to remove that element from my main list. I use the pop() method to remove an element when putting it to another list but pop() is not popping.

You can find my code below.

K = [15, -10, 9, 16, 7, -99, 27, 4001, 305]
single =[]
multi=[]
i = -1
for num in K:
    i += 1
    if num > 9 or num < -9:
        multi.append(num)  # o sayiyi multi listesine ekle
    else:
        single.append(num)
    K.pop(i)
    
print(single)
print(multi)
print(K)

Output:

[9,7]
[15, 27, 305]
[-10, 16, -99, 4001]

As you see at the end of the algorithm K should be empty. I don't want to use clear method. I want to remove the element while putting the element to another list.

efran
  • 11
  • 1

1 Answers1

0

That is because both the list decrease and the index increase, so that skips on value on each iteration

i  num  K
0   15  [15, -10, 9, 16, 7, -99, 27, 4001, 305]
1    9  [-10, 9, 16, 7, -99, 27, 4001, 305]
2    7  [-10, 16, 7, -99, 27, 4001, 305]
3   27  [-10, 16, -99, 27, 4001, 305]
4  305  [-10, 16, -99, 4001, 305]

You may use a a while loop

while K:
    num = K.pop(0)
    if num > 9 or num < -9:
        multi.append(num)
    else:
        single.append(num)
azro
  • 53,056
  • 7
  • 34
  • 70
  • Thanks for your helping. The problem has been solved. – efran Nov 14 '21 at 20:27
  • @efran You may think about [accepting an answer](https://stackoverflow.com/help/someone-answers) to reward those how helped you, or at least comment to explain what's missing ;) – azro Nov 14 '21 at 22:01