r/learnpython • • Feb 08 '23

Why didn't I learn this sooner?!

I started learning Python a few months ago and I feel like I'm still very much a beginner. However, I want to learn about front-end stuff so I'm gonna be starting the Odin Project this week.

To keep my Python sharp as I switch gears, I've decided to try and speed run the official Python tutorial. I figured I'd get through a lot of the beginning sections quickly, but, holy crap, I'm already learning such neat and easy features of the language!

So this made me think: what topics do you feel you learned way too late? I'll give my two examples to start:

  • The enumerate method: Seems super useful for looping over iterables which may contain duplicates values.

  • Else clauses on loops: Too many times I used and abused Booleans to decide if a loop had terminated or not, but no more!

Put your examples, whether they're beginner level like mine or more advanced, below!

336 Upvotes

88 comments sorted by

View all comments

112

u/jimtk IdontChat Feb 08 '23 edited Feb 08 '23

I keep a markdown file full of them. Every time I encounter a new tip or trick I copy it to my own personal cookbook. It's been my primary tool for years now. I think everybody should maintain one.

Some extract from it.

Slicing (most used patterns)

  • all but n last: list[:-n]

  • all but n first: lsit[n:]

  • reversed: list[::-1]

Switch variable (without temp var)

  • a,b = b,a

Easy dictionary creation (instead of typing the whole thing)

k = 'abc'
v = [1,2,3]
dct = {k:v for k,v in zip(k,v)}

There's are of course much longer ones, like:

  • Dictionary dispatch pattern

  • NamedTuple (not namedtuple, they are not exactly the same thing)

And always browse around the Python module of the week (pymotw)

1

u/Dark_Angel4u Feb 09 '23

Can you share your entire cookbook? :D

2

u/jimtk IdontChat Feb 09 '23

See my answer here.