Single Line Nested for Loops

Single Line Nested For 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")]

Python nested loop with two outputs in a single-line

It is possible, but unfolding it in 3 lines might be more readable, and therefore a better option than a list comprehension:

You have to use:

  • one way to repeatedly generate the constant value you want to interleave. - this can be done with itertools.repeat;
  • pack both values together for each iteration: the builtin zip does that;
  • iterate the packed values: the one coming from your normal source and the one injected: you need another for statement. I find it a bit counterintuitive that in comprehensions, nested loops are just nested as in normal code, but the expression making use of the loop values (v) in this case, is in the outermost part, as a prefix:
from itertools import repeat

result = [v for bundle in zip(repeat(99), [1,2,3,4,5]) for v in bundle]

How to write multiple for loops in one line of if condition in python? (specific to DOCX)

You have your for clauses reversed. You are trying to reference row in the first for clause and then define it in the second. That's why it doesn't work.

You mean

if any(cell.tables for row in table.rows for cell in row.cells):
...

Issue with single line nested for loop in Python

You should just split your input into chunks of 4 and then convert them directly to lists:

cleaned_output = [list(output[i:i+4]) for i in range(0, len(output), 4)]

Output:

[['0', '1', '2', '3'], ['4', '5', '6', '7'], ['8', '9', '1', '0'], ['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]

How to create two nested for loops in a single line in Julia

Correct, Julia allows you to tersely express nested for loops.

As an example, consider filling in a 3x3 matrix in column order:

julia> xs = zeros(3,3)
3×3 Array{Float64,2}:
0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0

julia> let a = 1
for j in 1:3, i in 1:3
xs[i,j] = a
a += 1
end
end

julia> xs
3×3 Array{Float64,2}:
1.0 4.0 7.0
2.0 5.0 8.0
3.0 6.0 9.0

The above loop is equivalent to this more verbose version:

julia> let a = 1
for j in 1:3
for i in 1:3
xs[i,j] = a
a += 1
end
end
end

This syntax is even supported for higher dimensions(!):

julia> for k in 1:3, j in 1:3, i in 1:3
@show (i, j, k)
end

Writing a single-line nested loop in Python

Possibly counter intuitively, in a nested list comprehension you need to follow the same order of the for loops as with the longhand version. So:

[data[((len(data) - 1) - (8 * i)) - (7 - n)] for i in range(int(len(data) / 8)) for n in range(8)]

Nested for loops in python in a single line

You could use a generator expression to nest the loops and add a filter that makes the IndexError handler obsolete:

candidates = ((x, y) for x in lister[0].conditions for y in x.codes if ',' in y.id)
for x, y in candidates:
if y.id.split(',')[1] == condition:
matcher = x.codenames

Readability would be improved more by using more meaningful names other than x and y here though:

candidates = ((cond, code) for cond in lister[0].conditions for code in cond.codes
if ',' in code.id)
for cond, code in candidates:
if code.id.split(',')[1] == condition:
matcher = cond.codenames

Alternating lines with Nested Loops

There are several ways to do it. First you should check how many lines you need to output. 5, so you need a loop doing something 5 times.

for i in range(5):

Now you need 2 loops to paste print the 2 line patterns (you already have them in your code)

 for b in range(10):
print("#", end = "")
print("")

and

for b in range(10):
print("*", end = "")
print("")

If you need to alternate between 2 values it's mostly the best to use the Modulo Operator.

So you can just switch between the 2 loops by % 2.

for i in range(5):
if i % 2 == 0:
for b in range(10):
print("#", end = "")
print("")
else:
for b in range(10):
print("*", end = "")
print("")


Related Topics



Leave a reply



Submit