Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python- My for loop only converts half the list from str to int

I want my code to cycle through each item of the list and convert it from str to int but it only converts half of the list and in an irregular order. My code:

for item in list:
    list.append(int(item))
    list.remove(item)
print (list)

For example if list is ['5', '6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8']

The final would be ['6', '8', '5', '4', '2', '8', 3, 6, 2, 6, 5, 5]

Which is only half converted and not in order.

I could do it another way but that is a lot longer so would like to fix this and add to my knowledge about for loops.

My knowledge and experience with Python is tiny, so I most probably won't understand unless it's really basic and jargon is explained.

like image 966
lolol Avatar asked Mar 01 '26 02:03

lolol


1 Answers

Using list comprehension:

l = ['5', '6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8']

output = [int(i) for i in l]
print(output)
[5, 6, 3, 5, 6, 2, 6, 8, 5, 4, 2, 8]

If you don't understand list comprehension you could use simple for loop:

l1 = []
for i in l:
     l1.append(int(i))

print(l1)
[5, 6, 3, 5, 6, 2, 6, 8, 5, 4, 2, 8]
like image 76
Anton Protopopov Avatar answered Mar 03 '26 16:03

Anton Protopopov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!