-1

I'm trying to learn how I can convert Python list comprehensions to a normal for-loop. I have been trying to understand it from the pages on the net, however when I'm trying myself, I can't seem to get it to work.

What I am trying to convert is the following:
1:

n, m = [int(i) for i in inp_lst[0].split()]

and this one (which is a little bit harder):
2:

lst = [[int(x) for x in lst] for lst in nested[1:]]

However, I am having no luck with it.

What I have tried:
1:

n = []
for i in inp_lst[0].split():
    n.append(int(i))
print(n)

If I can get some help, I will really appreciate it :D

Chris
  • 26,361
  • 5
  • 21
  • 42
Chrizzar
  • 55
  • 6
  • 2
    Your first example will only work if `inp_lst[0].split()` has exactly two elements (since it assigns to two targets), so you'd need to special-case the for loop to take account of that. That's not a great example for how to convert comprehension to loop. – BrenBarn Jan 30 '22 at 19:57
  • 2
    Also providing the input you're testing against, and what's the error message is generally a good idea. – avlec Jan 30 '22 at 20:02
  • I find this [answer](https://stackoverflow.com/questions/18072759/list-comprehension-on-a-nested-list/45079294#45079294) immensely useful when converting between for loops and list comprehensions. – quamrana Jan 30 '22 at 20:13
  • @BrenBarn That is exactly what I have. It is a great example, if that is what I need to do. – Chrizzar Jan 30 '22 at 21:46

1 Answers1

3

Generally speaking, a list comprehension like:

a = [b(c) for c in d]

Can be written using a for loop as:

a = []
for c in d:
    a.append(b(c))

Something like:

a, b = [c(d) for d in e]

Might be generalized to:

temp = []
for d in e:
    temp.append(c(d))

a, b = temp

Something like:

lst = [[int(x) for x in lst] for lst in nested[1:]]

Is no different.

lst = []
for inner_lst in nested[1:]:
    lst.append([int(x) for x in inner_lst])

If we expand that inner list comprehension:

lst = []
for inner_lst in nested[1:]:
    temp = []
    for x in inner_lst:
        temp.append(int(x))
    lst.append(temp)
Chris
  • 26,361
  • 5
  • 21
  • 42
  • 1
    Cool cool thanks, that work. I understand what i happening now :D I know that comprehension makes code easier to do some stuff and does now take up that much space compared to the expanded version. However, for me the expanded version is much more readable and makes understand more what is happening. So thanks for the help :D – Chrizzar Jan 30 '22 at 21:52
  • Feel free to accept the answer if you feel it has answered your question. – Chris Jan 30 '22 at 21:55
  • I feel kinda stupid right, but how would the expanded version of this look like then?: nested = [] nested = [val.split() for val in inp_lst[1:]] – Chrizzar Jan 30 '22 at 22:11
  • Oh never mind, I find out. So I learned something. It was simply the same as the other one, but without the temp = [] and the inder for loop. – Chrizzar Jan 30 '22 at 22:14