0

I was trying to practice nested for loops and I was trying to get the outer loop to only run each time. I tried using an if with indexes. The original code below will repeat everything in adj 3 times while I only want it to be once.

adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
  for y in fruits:
    print(x, y)

The output here would be:

red apple red banana red cherry big apple big banana big cherry tasty apple tasty banana tasty cherry

While I only want it to be red apple, big banana, and tasty cherry. So I tried to do the following code below, but I keep getting a general syntax error.

adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]


for x in adj:
    print(x)
    a = adj.index(x)
    print(a)
    for y in fruits:
        b = fruits.index(y)
        print(b)
        if int(a) = int(b):
            print(x, y)

Does anyone have any suggestions or tips on how to go about this? I am trying to do something similar for my project but I cannot get the x variable to no repeat for repeat for each y?

Hollywood
  • 3
  • 2
  • This is kind of indirect, but you basically want to do what's asked [here](https://stackoverflow.com/questions/2407398/how-to-merge-lists-into-a-list-of-tuples). Then you just need to print each pair as a separate step. – Carcigenicate Aug 21 '21 at 23:18
  • The syntax error is caused by using `=` in `if int(a) = int(b):` rather than `==`. `=` is used for assignment, `==` is testing equality. – Oli Aug 21 '21 at 23:24
  • what about `[print(x, y) for x in adj for y in fruits]` – mama Aug 21 '21 at 23:26
  • 1
    @mama this is equivalent to the first example, not the desired behaviour. Also, using list comprehensions for I/O makes for less readable code. – Oli Aug 21 '21 at 23:28
  • `if len(adj) == len(fruits): [print(adj[x], fruits[x]) for x in range(len(adj))]` – Moisés Cunha Aug 21 '21 at 23:29

2 Answers2

2

This is a perfect example where you can use zip():

adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x, y in zip(adj, fruits):
    print(x, y)

Output:

red apple
big banana
tasty cherry
j1-lee
  • 13,764
  • 3
  • 14
  • 26
1

In this case you should use the zip() built-in function like the following example:

adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x, y in zip(adj, fruits):
    print(x, y)

Note that you could use zip() with more than two arguments

adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
colors = ["green", "yellow", "red"]

for x, y, z in zip(adj, fruits, colors):
    print(x, y, z)
BatiDyDx
  • 11
  • 1