Search code examples
pythonlist-comprehension

How to convert a loop into a list comprehension


How can I write this loop using list comprehension?

t = [i.find_all('li') for i in soup.select('div.col.col-7-12')]
Des = []
for i in t:
    r = []
    Des.append(r)
    for j in i:
        n = j.text
        r.append(n)

Solution

  • t = [i.find_all('li') for i in soup.select('div.col.col-7-12')] 
    Des = [] 
    for i in t: 
        r = [] 
        Des.append(r) 
        for j in i: 
            n = j.text 
            r.append(n)
    

    Replace one loop:

    t = [i.find_all('li') for i in soup.select('div.col.col-7-12')] 
    Des = [] 
    for i in t:
        r = [j.text for j in i]
    

    Replace both loops:

    t = [i.find_all('li') for i in soup.select('div.col.col-7-12')] 
    Des = [[j.text for j in i] for i in t]
    

    Or:

    Des = [[j.text for j in i] for i in [i.find_all('li') for i in soup.select('div.col.col-7-12')]]
    

    However just because you can replace something with a long list comprehension doesnt mean you should, I think in this case two two-liner I wrote is still alright to read (could use some more clear variable names), the one-liner is definitely an overkill and super hard to read.