1

I am still relatively new to coding. I've been doing this for less than a year and most of the basics I completely understand now. However, every now and then I come across a type of for loop that I can't get my head around.

It usually goes like this:

x for x in list if x in otherList

I completley understand for loops and if statements. But that particular line of code always confuses me. Would anyone be able to provide a detailed explanation of what actually is happening there, please?

rramirez
  • 37
  • 4
  • 4
    it's called list comprehension, google should give you plenty of reading material! good luck – Matthias Aug 31 '22 at 09:24
  • 1
    That is not a valid statement in itself, it usually within [ ... ] or { ... } or ( ... ), it then is a list / dict / set comprehension or a a generator expression, etc. – luk2302 Aug 31 '22 at 09:24
  • 1
    Sorry, no. You first. Please explain each element of the code you have posted until you get stuck. – quamrana Aug 31 '22 at 09:24
  • Please read [the official tutorial on list comprehensions](https://docs.python.org/3.10/tutorial/datastructures.html#list-comprehensions). – AKX Aug 31 '22 at 09:25

2 Answers2

3

It's called a list comprehension if it's in brackets []:

This:

new_list = [x for x in my_list if x in other_list]

Is equivalent to this:

new_list = []
for x in my_list:
    if x in other_list:
        new_list.append(x)

If it's in parentheses () it's called a generator:

This:

new_list = (x for x in my_list if x in other_list)

Is sort of equivalent to this:

def foo():
    for x in my_list:
        if x in other_list:
            yield x

new_list = foo()

You might want to read this question and answer to understand more about generators and yielding functions.

The Thonnu
  • 3,578
  • 2
  • 8
  • 30
0

This is used within a list comprehension and the if statement acts as a filter.

You may begin with a list of all numbers from 0-9:

mynums = range(10)

But then you might want only the even numbers in a new list:

myevennums=[]
for i in mynums:
    if mynums%2 ==0:
       myevennums.append(i)

That works but so many keystrokes

So python allows list comprehensions:

myevennums = [i for i in mynums if i%2==0]

The condition could be anything, including membership in another list:

evens_to_20 = list(range(0,21,2))

Then you could create a list with the elements of your list that are also in the other list:

myevennums = [i for i in mynums if i in evens_to_20]

In general, when you see a statement like that you can always expand it as:

Y_comprehension = [i for i in X if condition(i)] 
# the same as
Y_loop=[]
for i in X:
    if condition(i):
        Y_loop.append(i)
assert Y_comprehension == Y_loop

If the condition really is very simple, the list-comprehension is usually the better choice. If it starts to get complicated, you probably want the loop or an intermediate function def condition(item): ...

mmdanziger
  • 4,466
  • 2
  • 31
  • 47