If you're frequently iterating over a Cartesian product like in your example, you might want to investigate Python 2.6's itertools.product -- or write your own if you're in an earlier Python.
from itertools import product
for y, x in product(range(3), repeat=2):
do_something()
for y1, x1 in product(range(3), repeat=2):
do_something_else()
Answer from alicederyn on Stack OverflowIn python is there an easier way to write 6 nested for loops? - Stack Overflow
can't understand nested for loops 😭 (need help!)
Nested loops
[Python] Can someone please explain to me how nested for loops work using this example. I don't understand how it works
Videos
If you're frequently iterating over a Cartesian product like in your example, you might want to investigate Python 2.6's itertools.product -- or write your own if you're in an earlier Python.
from itertools import product
for y, x in product(range(3), repeat=2):
do_something()
for y1, x1 in product(range(3), repeat=2):
do_something_else()
This is fairly common when looping over multidimensional spaces. My solution is:
xy_grid = [(x, y) for x in range(3) for y in range(3)]
for x, y in xy_grid:
# do something
for x1, y1 in xy_grid:
# do something else
We have a practical exam coming up on my uni regarding nested for loop in which I struggle to. Can you help me understand how does it work. I know that it is a loop within a loop but I can't logically decide what values to put in the inner loop (the range and the increment). I can't wrap my head around it. 😭
My professor typically give us exercises like these:
Exercise 1: 9 7 7 7 5 5 5 5 5 3 3 3 3 3 3 3 Exercise 2: 8 6 6 4 4 4 2 2 2 2 0 0 0 0 0 Exercise 3: 4 4 4 4 4 4 4 4 3 3 3 3 3 3 2 2 2 2 1 1 Exercise 4: 2 2 2 2 2 2 4 4 4 4 6 6 Exercise 5: 1 1 1 1 1 5 5 5 9 Exercise 6: 5 5 10 10 10 10 15 15 15 15 15 15 Exercise 7: 6 444 22222 Exercise 8: 6 444 2222
For context,I am currently following Programming with Mosh's beginner python course(for 4 days) and was on the solution to the challenge for the nested loop part.
I have seen that when you type
numbers = [5, 2, 5, 2, 2]
for x_count in numbers:
for count in range(x_count):
print(count)
what is shown are the numbers
0
1
2
3
4
0
1
0
1
2
3
4
0
1
0
1
and then if you type
numbers = [5, 2, 5, 2, 2]
for x_count in numbers:
output = ''
for count in range(x_count):
output += 'x'
print(output)
then it shows up as
xxxxx
xx
xxxxx
xx
xx instead of
x
xx
xxx
xxxx
x
x
xx
xxx
xxxx
x
x
Which is what i thought should happen. Why? I want to understand rather than just mermorise and move on.
userInput = int(input())
for i in range(userInput):
for j in range(i,userInput):
print('*', end=' ')
print()input is: 3
the output is:
* * * * * * I have been looking at videos and different websites, but i cannot understand it.
I am learning python and i dont really understand the importance of nested loops
The best source of information is the official Python tutorial on list comprehensions. List comprehensions are nearly the same as for loops (certainly any list comprehension can be written as a for-loop) but they are often faster than using a for loop.
Look at this longer list comprehension from the tutorial (the if part filters the comprehension, only parts that pass the if statement are passed into the final part of the list comprehension (here (x,y)):
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
It's exactly the same as this nested for loop (and, as the tutorial says, note how the order of for and if are the same).
>>> combs = []
>>> for x in [1,2,3]:
... for y in [3,1,4]:
... if x != y:
... combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
The major difference between a list comprehension and a for loop is that the final part of the for loop (where you do something) comes at the beginning rather than at the end.
On to your questions:
What type must object be in order to use this for loop structure?
An iterable. Any object that can generate a (finite) set of elements. These include any container, lists, sets, generators, etc.
What is the order in which i and j are assigned to elements in object?
They are assigned in exactly the same order as they are generated from each list, as if they were in a nested for loop (for your first comprehension you'd get 1 element for i, then every value from j, 2nd element into i, then every value from j, etc.)
Can it be simulated by a different for loop structure?
Yes, already shown above.
Can this for loop be nested with a similar or different structure for loop? And how would it look?
Sure, but it's not a great idea. Here, for example, gives you a list of lists of characters:
[[ch for ch in word] for word in ("apple", "banana", "pear", "the", "hello")]
You might be interested in itertools.product, which returns an iterable yielding tuples of values from all the iterables you pass it. That is, itertools.product(A, B) yields all values of the form (a, b), where the a values come from A and the b values come from B. For example:
import itertools
A = [50, 60, 70]
B = [0.1, 0.2, 0.3, 0.4]
print [a + b for a, b in itertools.product(A, B)]
This prints:
[50.1, 50.2, 50.3, 50.4, 60.1, 60.2, 60.3, 60.4, 70.1, 70.2, 70.3, 70.4]
Notice how the final argument passed to itertools.product is the "inner" one. Generally, itertools.product(a0, a1, ... an) is equal to [(i0, i1, ... in) for in in an for in-1 in an-1 ... for i0 in a0]