Search code examples
pythonlist-comprehension

How can I convert a list comprehension to a normal for loop?


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


Solution

  • 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)