Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are containers always iterable?

enter image description here

Is there a scenario where the container is not iterable, according to this graph?

like image 916
Pythoner Avatar asked Jun 18 '26 15:06

Pythoner


2 Answers

Depends on what you mean by always. According to collections.abc

  • a container is an object that implements __contains__ method
  • an iterable is an object that implements __iter__ (or __getitem__, as a fallback)

So, theoretically, no, you can implement a container that is not an iterable. However, all standard python containers (and most containers implemented by libraries) are also iterable.

like image 125
blue_note Avatar answered Jun 20 '26 05:06

blue_note


All a container does is give you the if x in y and if x not in y syntax.

You could have like a Range(min: float, max: float) that implements __contains__ as returning True for any number in the range, which would allow you to write if 3.14 not in provided_range etc. And that would not be iterable.

The graph is a bit misleading in suggesting that {list, set, dict} comprehension are the only interesting things to produce containers.

like image 33
Dax Fohl Avatar answered Jun 20 '26 05:06

Dax Fohl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!