Langfao Langfao - 8 months ago 37
Python Question

How do I make a loop to look through the elements of a list?

Am fairly new to python and coding in general. So I have a defined list and I'm trying to make a loop that looks through the elements in a list until it matches what I'm looking for and records the position it is in the list.

list = [1, 2, 3, 4]
x = 3
for x in list:
if x == list
print(x, list.index(x))

This is my attempt but it doesn't work at all.


You shouldn't loop for x in list. That will make your x value [1,2,3,4] not 3 anymore and beware with the indentation in python. Python is sensitive with Indentation. Maybe this is the code you're looking for:

list = [1, 2, 3, 4]
x = 3
for i in list:
    if (i == x):
        print(i, list.index(i))

I forgot that list is a built-in syntax. We shouldn't use list as variable. Just change it with 'list1' or anything except the built-in syntax name. Here some list of built-in syntax in python