Programming improvements 3

A few things of the many things I learned last months in Python.

For and while loops have an else option

I used to write code like this:

helper = False
for something in some_list:
    if condition:
       helper = True
if helper == False:

That can be done so much easier:

for something in some_list:
    if condition:
else:    # break wasn't called in the loop

A similar option exist for while loops.

Few other little things were:

if helper == False:          ->            if not helper:

def method(somevar=""):      ->            def method(somevar=None):
    if somevar != "":                          if somevar:

List comprehensions were also a revelation. Instead of using:

newlist = []
for entry in some_list:
    if condition:

condition could be something like “entry > 0”. Using a list comprehension, that can be a one liner and is also faster in the execution:

newlist = [entry for entry in some_list if condition]

While I still feel, it would have been nice, if I’d have learned these little things before (which comes from the thought I would be liked more, and from the expectation of perfectionism by me and because of that I also think others expect perfectionism from me – which is just not achievable), it is nice to pick new things up now. While I thought in my 20s that in many areas of life I can stop learning at some point, in the last years I learned that learning will never end in any part of life, and that is good! Because if I stop being willing to learn, I will go backwards.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s