-1

I'm sure this question was asked time ago, but I can't find it because I don't know how to search for it.

Lately I'm seeing this kind of for everywhere. So I was wondering how does it work, what's it using for, and these stuff. I would be grateful if you could put multiple examples, equivalences in relation to other codes, etc. Thanks a lot.

This is the kind of for I'm asking for.

x = [x for x in range(len(ys))] 

or

n = [ [ls[i] for i in t] for t in indexes(len(ls),k) ] 

Thanks!

  • 3
    it is called "list comprehension" - and it has siblings "generator expression" and "set comprehension" and "dict comprehension" – jsbueno Apr 17 '20 at 16:20

1 Answers1

2

This is a list comprehension.

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

The basic structure you'll see often is [EXP for VAR in LIST] which iterates LIST, and for each element in the list, EXP is evaluated with VAR set to the respective list element.

Let's start with a list x that contains the integers 0 to 9:

>>> x = range(10)
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

You can use a list comprehension in a similar manner to map() to alter each element:

>>> [i * 2 for i in x]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

You can use it to filter out elements:

>>> [i for i in x if i % 2 == 0]
[0, 2, 4, 6, 8]

You can do both at the same time:

>>> [i * 2 for i in x if i % 2 == 0]
[0, 4, 8, 12, 16]

You don't even have to reference the iteration variable:

>>> ["foo" for i in x if i % 2 == 0]
['foo', 'foo', 'foo', 'foo', 'foo']

The second example in your question is an example of how to project a list for each element; in this particular case, the outer list being traversed contains iterables. This expression maps the inner iterables to lists. This can be used to map nested lists.

cdhowie
  • 158,093
  • 24
  • 286
  • 300