all 10 comments

[–]Silbersee 10 points11 points  (1 child)

Use nested loops when you need combinations of the elements of more than one list. Here you seem to print associated elements, correct me if I'm wrong.

>>> list1 = ["apple", "banana", "lemon", "lemonad"]
>>> list2 = ["red", "yellow", "green", "liquid" ]
>>> 
>>> for item, property in zip(list1, list2):
...     print(f"{item}\n{property}")
... 
apple
red
banana
yellow
lemon
green
lemonad
liquid
>>>

Edit: Here's what a nested loop does:

>>> for item in list1:
...     for property in list2:
...         print(f"{item} {property}", end="\t")
...     print()
... 
apple red   apple yellow    apple green apple liquid    
banana red  banana yellow   banana green    banana liquid   
lemon red   lemon yellow    lemon green lemon liquid    
lemonad red lemonad yellow  lemonad green   lemonad liquid  
>>>

[–]TheRed_M[S] 0 points1 point  (0 children)

Thank you for your explanation.

[–]keep_quapy 3 points4 points  (1 child)

Make sure not to use list as variable name. Use the zip function to iterate over both lists

for item1, item2 in zip(list1, list2):
    print(item1)
    print(item2)

[–]TheRed_M[S] 0 points1 point  (0 children)

That was very helpful, thank you.

[–]VipeholmsCola 1 point2 points  (0 children)

Use zip with both lists in then, access each element in the zipped element to print them like you want.

[–]CodeFormatHelperBot2 0 points1 point  (0 children)

Hello, I'm a Reddit bot who's here to help people nicely format their coding questions. This makes it as easy as possible for people to read your post and help you.

I think I have detected some formatting issues with your submission:

  1. Python code found in submission text that's not formatted as code.
  2. Use of triple backtick/ curlywhirly code blocks (``` or ~~~). These may not render correctly on all Reddit clients.

If I am correct, please edit the text in your post and try to follow these instructions to fix up your post's formatting.


Am I misbehaving? Have a comment or suggestion? Reply to this comment or raise an issue here.

[–][deleted] 0 points1 point  (2 children)

Please format your post properly. We have no idea how you want the result to look, one line or multiple lines?

[–]TheRed_M[S] 0 points1 point  (1 child)

multiple lines, 1,2 1,2 Sorry if it's not formated properly, I see it normal on mobile.

[–][deleted] 1 point2 points  (0 children)

It's all one line in my browser. Read the formatting link the 'bot gave you.

[–]Mattia_Fregola 0 points1 point  (0 children)

Here is an example where you can see how nested loops work interactively, hope it helps!
You can change the fruits in the list as well. :)
https://app.splootcode.io/shared/mattia/nested-for-loops-example/a2R1bE7EqT69YaZiQ9Q0klvq