Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Sorting Data for loop and if statement

data = ['cat', 'dog', 'None', 'Turtle', 'None']
new_data = []
for item in data:
    if item == 'None':
        new_data.append(data.index(item))
print new_data

>> [2,2]

How do I go about getting to this store new data as [2,4]? This is what I want. Thank you!

like image 371
phales15 Avatar asked Dec 06 '25 10:12

phales15


1 Answers

Use enumerate() while looping. This will track both, the current item and its index:

[index for index, x in enumerate(data) if x == "None"]
like image 164
Sven Marnach Avatar answered Dec 08 '25 01:12

Sven Marnach



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!