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
break
if helper == False:
do_something()
That can be done so much easier:
for something in some_list:
if condition:
break
else: # break wasn't called in the loop
do_something
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:
newlist.append(entry)
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.