Python Comprehensions: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 17: Line 17:
<syntaxhighlight lang='py'>
<syntaxhighlight lang='py'>
[<expression> for <var> in <iterable>]
[<expression> for <var> in <iterable>]
</syntaxhighlight>
This example iterates over a list of custom object instances and produces a comma-separated list of their <code>__str__()</code> representations, which printing the list with <code>print()</code> does not do:
<syntaxhighlight lang='py'>
class C:
  def __init__(self, i):
    self.i = I
  def __str__(self):
    return "<" + self.i + ">"
l = [C(1), C(2), C(3)]
</syntaxhighlight>
<syntaxhighlight lang='py'>
print(l)
</syntaxhighlight>
displays:
<syntaxhighlight lang='text'>
...
</syntaxhighlight>
The following list comprehension:
<syntaxhighlight lang='py'>
print(', '.join([str(i) for i in l]))
</syntaxhighlight>
displays:
<syntaxhighlight lang='text'>
...
</syntaxhighlight>
</syntaxhighlight>



Revision as of 01:40, 9 July 2022

Internal

TODO

  • PROCESS IPy Comprehensions Page 84.
  • PROCESS PyOOP "Comprehensions" + "List comprehensions" + "Set and dictionary comprehensions"

Overview

A comprehension is a compact way of creating a data structure from one or more iterators. They are essentially loops with a more compact syntax.

List Comprehensions

A list comprehension produces a list from an iterable type by applying an expression to each of the elements, and optionally a condition.

Simple List Comprehension

[<expression> for <var> in <iterable>]

This example iterates over a list of custom object instances and produces a comma-separated list of their __str__() representations, which printing the list with print() does not do:

class C:
  def __init__(self, i):
    self.i = I
  def __str__(self):
    return "<" + self.i + ">"

l = [C(1), C(2), C(3)]
print(l)

displays:

...

The following list comprehension:

print(', '.join([str(i) for i in l]))

displays:

...

Conditional List Comprehension

[<expression> for <var> in <iterable> if <condition>]