Counting Occurrences Using Comprehension

suggest change

When we want to count the number of items in an iterable, that meet some condition, we can use comprehension to produce an idiomatic syntax:

# Count the numbers in `range(1000)` that are even and contain the digit `9`:
print (sum(
    1 for x in range(1000) 
    if x % 2 == 0 and
    '9' in str(x)
))
# Out: 95

The basic concept can be summarized as:

  1. Iterate over the elements in range(1000).
  2. Concatenate all the needed if conditions.
  3. Use 1 as expression to return a 1 for each item that meets the conditions.
  4. Sum up all the 1s to determine number of items that meet the conditions.

Note: Here we are not collecting the 1s in a list (note the absence of square brackets), but we are passing the ones directly to the sum function that is summing them up. This is called a generator expression, which is similar to a Comprehension.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


List comprehension:
* Syntax
* Counting Occurrences Using Comprehension

Table Of Contents
1 List comprehension
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve