Nested loops, we all love them. Or do we? Five levels of indentation later you are not so sure. Your code starts to look ugly and you wish there was another way. Fortunately there is! One of the functions provided by itertools, product(), can replace your loops with a function call. So what is itertools.product? It's a function that takes a number of iterables and returns their Cartesian product, or in simpler terms, all ordered tuples with elements coming from each of the iterables. Product of [1, 2] and ['a', 'b', 'c'] would result in tuples: (1, 'a'), (1,...
Tag: PyTips
In PyTips I'll be talking about Python features, standard libraries, and interesting packages found on PyPi. The idea is to have a short write up and accompanying code snippets for all Python things that I found useful and interesting. These will be mostly aimed at beginners, and I hope that you too, my reader, will find them helpful. Problem A common idiom while looping over collection is to use helper variable to store index of the element currently worked on. For example, we want to convert IP address from dotted-decimal to the decimal format: my_ip = '10.16.32.113'...