Python Comprehensions: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 27: Line 27:
     self.i = i  
     self.i = i  
   def __str__(self):
   def __str__(self):
     return "<" + self.i + ">"
     return "<" + str(self.i) + ">"


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

Revision as of 01:47, 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>]

The list comprehension moves the loop inside square brackets. 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 "<" + str(self.i) + ">"

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

displays:

[<__main__.C object at 0x102f06b20>, <__main__.C object at 0x1030159d0>, <__main__.C object at 0x10302c9a0>]

The following list comprehension:

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

displays:

...

Conditional List Comprehension

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