The for syntax and count() behave strangely in python.

Asked 2 years ago, Updated 2 years ago, 122 views

data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
for i in data:
    if data.count(i) == 1:
        data.remove(i)
print(data)

output: [2,4,6,8,10,12,14]

Why does an odd number work when I tried to erase the only value?

python for count

2022-09-22 12:59

1 Answers

Changing the data inside the for routine that processes the data also affects the iterator i.

In this case, the intended result can be obtained by storing the results in another list within the for routine, as shown below.

data = [1,2,2,2,3,3,4,4,5,5,6,6,6,7,8,9,10,11,12,13,14]
output = []
for i in data:    
    If data.count(i) > 1: # Elements with only 1 present will not be appended
        output.append(i)
print(output) 


2022-09-22 12:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.