How can I limit iterations of a loop?

How can I limit iterations of a loop in Python? for index, item in enumerate(items): print(item) if index == limit: break Is there a shorter, idiomatic way to write the above? How? Including the index zip stops on the shortest iterable of its arguments. (In contrast with the behavior of zip_longest, which uses the longest … Read more

Only index needed: enumerate or (x)range?

I would use enumerate as it’s more generic – eg it will work on iterables and sequences, and the overhead for just returning a reference to an object isn’t that big a deal – while xrange(len(something)) although (to me) more easily readable as your intent – will break on objects with no support for len…

How to make a continuous alphabetic list python (from a-z then from aa, ab, ac etc)

Use itertools.product. from string import ascii_lowercase import itertools def iter_all_strings(): for size in itertools.count(1): for s in itertools.product(ascii_lowercase, repeat=size): yield “”.join(s) for s in iter_all_strings(): print(s) if s == ‘bb’: break Result: a b c d e … y z aa ab ac … ay az ba bb This has the added benefit of going … Read more

How to enumerate an enum with String type?

This post is relevant here https://www.swift-studies.com/blog/2014/6/10/enumerating-enums-in-swift Essentially the proposed solution is enum ProductCategory : String { case Washers = “washers”, Dryers = “dryers”, Toasters = “toasters” static let allValues = [Washers, Dryers, Toasters] } for category in ProductCategory.allValues{ //Do something }

What does enumerate() mean?

The enumerate() function adds a counter to an iterable. So for each element in cursor, a tuple is produced with (counter, element); the for loop binds that to row_number and row, respectively. Demo: >>> elements = (‘foo’, ‘bar’, ‘baz’) >>> for elem in elements: … print elem … foo bar baz >>> for count, elem … Read more