-7

I'm currently working on a school assignment that involves me learning Python and I'm currently stuck on 'For Loops.' I'm stuck on understanding how they work and their syntax.

I have an example of code I've been trying to wrap my head around but just can't get it.

simple_list = ["Jack", "Dianne", "Alfred", "Erik"]
for x in simple_list:
    print(x)

This is the code I've been focusing on and I don't understand why it prints a name from the simple list. I also want to know what 'in' does as I couldn't find anything online that helped me understand it.

Thanks!

DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
  • What do you expect it to print? – Mayank Porwal Apr 30 '20 at 21:25
  • 1
    Please repeat [on topic](https://stackoverflow.com/help/on-topic) from the intro tour. These are questions handled quite well by the many Python tutorials and other educational materials on line. As such, this is not a Stack Overflow issue. – Prune Apr 30 '20 at 21:25
  • Please read: https://wiki.python.org/moin/ForLoop – Gabio Apr 30 '20 at 21:26
  • https://stackoverflow.com/questions/4170656/for-loop-in-python – sahasrara62 Apr 30 '20 at 21:27
  • 1
    `for a in b` is perfectly normal English, and in Python it doesn't have any weird meaning or side effect. `for cookie in jar`: do something with every cookie – regardless whether it's chocolate chip, hazelnut, or peanuts. You'll know what it is the moment you pick one. – Jongware Apr 30 '20 at 21:28
  • "I couldn't find anything online that helped me understand it." Rlly? :D – Henry Harutyunyan Apr 30 '20 at 21:28

3 Answers3

3

You can think like this:

for EVERY ITEM in THIS LIST:
    print(THIS ITEM)
Rafael
  • 525
  • 7
  • 20
2
items = ["Jack", "Dianne", "Alfred", "Erik"]
for item in items:
    print(item)

Look at it as a for each instead of the class for with indices.

for (each) item in items:
    print(item)
2

For loops go over every item in a list. In this case you have a list

simple_list = ["Jack", "Dianne", "Alfred", "Erik"]

Now the for loop is going to look at every item in the list and do whatever is in the for loop with it. In this case, it will print it.

I'd recommend having a look at http://www.pythontutor.com/ to get a better feel for this sort of thing.

Nathan
  • 3,558
  • 1
  • 18
  • 38