How come regex match objects aren’t iterable even though they implement __getitem__?

There are lies, damned lies and then there is Python documentation. Having __getitem__ for a class implemented in C is not enough for it to be iterable. That is because there are actually 2 places in the PyTypeObject where the __getitem__ can be mapped to: tp_as_sequence and tp_as_mapping. Both have a slot for __getitem__ ([1], … Read more

collections.Iterable vs typing.Iterable in type annotation and checking for Iterable

Due to PEP 585 – Type Hinting Generics In Standard Collections, Python’s standard library container types are also able to accept a generic argument for type annotations. This includes the collections.abc.Iterable class. When supporting only Python 3.9 or later, there is no longer any reason to use the typing.Iterable at all and importing any of … Read more

Collection to Iterable

A Collection is an Iterable. So you can write: public static void main(String args[]) { List<String> list = new ArrayList<String>(); list.add(“a string”); Iterable<String> iterable = list; for (String s : iterable) { System.out.println(s); } }

Why aren’t Enumerations Iterable?

As an easy and clean way of using an Enumeration with the enhanced for loop, convert to an ArrayList with java.util.Collections.list. for (TableColumn col : Collections.list(columnModel.getColumns()) { (javax.swing.table.TableColumnModel.getColumns returns Enumeration.) Note, this may be very slightly less efficient.

Unittest’s assertEqual and iterables – only check the contents

Python 3 If you don’t care about the order of the content, you have the assertCountEqual(a,b) method If you care about the order of the content, you have the assertSequenceEqual(a,b) method Python >= 2.7 If you don’t care about the order of the content, you have the assertItemsEqual(a,b) method If you care about the order … Read more

Shortest way to get first item of `OrderedDict` in Python 3

Programming Practices for Readabililty In general, if you feel like code is not self-describing, the usual solution is to factor it out into a well-named function: def first(s): ”’Return the first element from an ordered collection or an arbitrary element from an unordered collection. Raise StopIteration if the collection is empty. ”’ return next(iter(s)) With … Read more

Why does Java not allow foreach on iterators (only on iterables)? [duplicate]

So I have a somewhat reasonable explanation now: Short version: Because the syntax also applies to arrays, which don’t have iterators. If the syntax were designed around Iterator as I proposed, it would be inconsistent with arrays. Let me give three variants: A) as chosen by the Java developers: Object[] array; for(Object o : array) … Read more