Search code examples
pythonperformancelist-comprehension

Converting For Loops To List Comprehensions


I was trying to understand List Comprehensions because I needed to improve performance on my project.

I believe this is how they work but please correct me if I am wrong.

To convert a for loop into a list comprehension the below for loop -

for A in B:
 if Condition:
  List.append(A)

would turn into

E = [A for A in B if Condition]

I didn't realize this was a duplicate. If the answers on this post were unsatisfactory, you can see the other post at the top of this one.


Solution

  • I'm not sure if I understand what you asked correctly, but generally if you have a for loop like this :

    some_list = []
    for A in B:
        if condition:
            some_list.append(A)
    

    It's equivalent list comprehension is :

    some_list = [A for A in B if condition]
    

    If you have an else for your condition, it would be a little different. Consider the following example :

    some_list = []
    for A in B:
        if condition:
            some_list.append(value1)
        else :
            some_list.append(value2)
    

    It would become like this :

    some_list = [value1 if condition else value2 for A in B]