1

this is my code so far

print("L = ",[4,10,4,2,9,5,4])

Startlist = [4,10,4,2,9,5,4]
usrinput = int(input("Enter an element to search for in the list: "))
for i in [i for i,x in enumerate(Startlist) if x == usrinput]:
    print(i)

I'm trying to however make a new list from the for loops printed numbers.This is the sample run i got by entering 4

L =  [4, 10, 4, 2, 9, 5, 4]
Enter an element to search for in the list: 4
0
2
6

how could i turn the 0 2 6 into [0,2,6]?

Thanks for any responses

1
  • You already have the list here: [i for i,x in enumerate(Startlist) if x == usrinput] Commented Oct 8, 2013 at 18:25

2 Answers 2

3

You already made the list! The heavy lifting in your code is in the temporary array you created and iterated over.

 newlist = [i for i,x in enumerate(Startlist) if x == usrinput]
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! yeah i clearly was following traditional for loop structure too much to notice there was no need to print(i) separately
3

Just print the list comprehension:

print([i for i,x in enumerate(Startlist) if x == usrinput])

1 Comment

@user2840144 You should probably accept one of these answers, by clicking the tick mark next to the one you like.

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.