LinkedIn Reddit icon

Dunder Doc

by Valdir Stumm Jr

The curious case of the else in Python loops

One of the first things to stand out when I was starting with Python was the else clause. I guess everyone knows the normal usage of such clauses in any programming language, which is to define an alternate path for the if condition. Oddly enough, in Python we can add else clauses in loop constructions, such as for and while. For example, this is valid Python: for number in some_sequence: if is_the_magic_number(number): print('found the magic number') break else: print('magic number not found') Notice how the else is aligned with the for and not with the if.

Drop Duplicates from a List in Order

Let’s say you have a list containing all the URLs extracted from a web page and you want to get rid of duplicate URLs. The most common way of achieving that might be building a set from that list, given that such operation automatically drops the duplicates. Something like: >>> urls = [ 'http://api.example.com/b', 'http://api.example.com/a', 'http://api.example.com/c', 'http://api.example.com/b' ] >>> set(urls) {'http://api.example.com/a', 'http://api.example.com/b', 'http://api.example.com/c'} The problem is that we just lost the original order of the list.