Skip to content

Commit 1b8d9ef

Browse files
committed
Add new example: Counting the booleans
* Moves the "Booleans are subclass of int" example from "Minor Ones" list to a new example.
1 parent 82bbded commit 1b8d9ef

File tree

1 file changed

+39
-7
lines changed

1 file changed

+39
-7
lines changed

README.md

Lines changed: 39 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1377,6 +1377,44 @@ Before Python 3.5, the boolean value fo `datetime.time` object was considered to
13771377

13781378
---
13791379

1380+
### Counting the booleans
1381+
1382+
```py
1383+
# A simple example to count the number of boolean and
1384+
# integers in an iterable of mixed data types.
1385+
mixed_list = [False, 1.0, "some_string", 3, True, [], False]
1386+
integers_found_so_far = 0
1387+
booleans_found_so_far = 0
1388+
1389+
for item in mixed_list:
1390+
if isinstance(item, int):
1391+
integers_found_so_far += 1
1392+
elif isinstance(item, bool):
1393+
booleans_found_so_far += 1
1394+
```
1395+
1396+
**Outuput:**
1397+
```py
1398+
>>> booleans_found_so_far
1399+
0
1400+
>>> integers_found_so_far
1401+
4
1402+
```
1403+
1404+
#### 💡 Explanation:
1405+
1406+
* Booleans are a subclass of `int`
1407+
```py
1408+
>>> isinstance(True, int)
1409+
True
1410+
>>> isinstance(False, int)
1411+
True
1412+
```
1413+
1414+
* See this StackOverflow [answer](https://stackoverflow.com/a/8169049/4354153) for rationale behind it.
1415+
1416+
---
1417+
13801418
### Needle in a Haystack
13811419

13821420
Almost every Python programmer would have faced this situation.
@@ -1508,13 +1546,7 @@ a, b = a[b] = {}, 5
15081546
+ `[] = ()` is a semantically correct statement (unpacking an empty `tuple` into an empty `list`)
15091547
+ `'a'[0][0][0][0][0]` is also a semantically correct statement as strings are iterable in Python.
15101548
+ `3 --0-- 5 == 8` and `--5 == 5` are both semantically correct statments and evalute to `True`.
1511-
* Booleans are a subclass of `int`
1512-
```py
1513-
>>> isinstance(True, int)
1514-
True
1515-
>>> isinstance(True, float)
1516-
False
1517-
```
1549+
15181550
* Python uses 2 bytes for local variable storage in functions. In theory, this means that only 65536 variables can be defined in a function. However, python has a handy solution built in that can be used to store more than 2^16 variable names. The following code demonstrates what happens in the stack when more than 65536 local variables are defined (Warning: This code prints around 2^18 lines of text, so be prepared!):
15191551
```py
15201552
import dis

0 commit comments

Comments
 (0)