3
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!

4 Answers 4

6

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

[index for index, x in enumerate(data) if x == "None"]
Sign up to request clarification or add additional context in comments.

Comments

2
for idx, item in enumerate(data):
    if item == 'None':
        new_data.append(idx)

better yet, just use a list comprehension as in Sven's answer

Comments

1

Try:

In [1]: data = ['cat', 'dog', 'None', 'Turtle', 'None']

In [2]: [i for i,val in enumerate(data) if val == 'None']
Out[2]: [2, 4]

Comments

1

data.index(item) only returns the position of first occurance of the item in your list. You could simply do this:

for i in range(0,len(data)):
  if data[i] == 'None':
    new_data.append(i)

this should give you the required output

OR

check out Sven's answer

5 Comments

why is my python spitting out [2, 2] when i do this your way ^?
@aaronphalen it should give [2,4]. It does for me.
@unni I agree, but got some odd reasons my python is spitting out [2,2]. I have tried opening a new shell and I get the same thing. What could be the issue?
@aaronphalen i'm not sure. I think you should go with Sven's answer though. As Tim pointed out thats more Pythonic
@SvenMarnach: oops, you're right. I just double-checked it; lookup indeed is O(1). Thanks for setting me straight on this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.