The reason it prints "three" is because you didnt define your array. The equivalent to what you're doing is:
arr = []
for i in array :
if i == "two" :
arr.push(i)
print(i)
You are asking for the last element it looked through, which is not what you should be doing. You need to be storing the array to a variable in order to get the element.
The english equivalent of what you are doing is:
You: "I need you to print all the elements in this array that equal two, but in an array. And each time you cycle through the list, define the current element as I."
Computer: "Here: ["two"]"
You: "Now tell me 'i'"
Computer: "'i' is equal to "three"
You: "Why?"
The reason 'i' is equal to "three" is because three was the last thing that was defined as I
the computer did:
i = "one"
i = "two"
i = "three"
print(["two"])
Because you asked it to.
If you want the index, go here
If you want the values in an array, define the array, like this:
MyArray = [(i) for i in my_list if i=="two"]
[i for i in my_list if ...]
. If you want to find one item matching some criteria, consider usingnext
; e.g.x = next(i for i in my_list if ...)
"two" in mylist
(which returns a boolean) ormylist.index("two")
(which returns the position of the found string)? Since you already have the string you're looking for, it's pointless to have it returned yet again by the search, isn't it?