r/learnpython • u/dangerlopez • 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!
4
Feb 08 '23
This looks really amazing! I hadn't heard about this until now. Thanks for shining some light on this! I'm gonna work through this myself I think.
For me, dictionaries and how to iterate their data are a tough concept for me..I just can't seem to understand how to properly nest a dictionary or then to use it's data properly.
3
u/dangerlopez Feb 08 '23
Yea, when they get nested they can be tough. The methods keys(), values(), and items() are what I always rely on. Good luck!
1
Feb 08 '23 edited Feb 08 '23
The methods keys(), values(), and items() are what I always rely on. Good luck!
Just a quibble - there aren't really very many uses for
dict.keys(), given that iterating over the dictionary is the same as iterating over itskeys(), a little faster, uses a little less memory, and a little less typing.d = {i: str(i) for i in range(4)} assert list(d) == list(d.keys()) print(*d.keys()) # Prints 0, 1, 2, 3 print(*d) # Prints 0, 1, 2, 3 for k in d.keys(): pass for k in d: # the same pass
keys()does one very important thing - it changes when the underlyingdictchanges. But often that isn't even what you want.In many projects, you can find and replace
'.keys()'with''and have everything work exactly the same.1
u/synthphreak Feb 08 '23
You can also do set operations with
dict.keys(). To do that another way, you’d need to callsete.g.,set(dict).
8
u/WhipsAndMarkovChains Data Scientist Feb 08 '23
Enumerate is great but what does it have to do with duplicate values?
2
u/cybervegan Feb 08 '23
In the sense that each value you get, has an index with it, so your code can more easily deal with each one separately. It's not the primary use, I'll grant you, but it's useful in that situation. It's more often used to get the index of list items without having to manually increment a loop counter, and without having to index elements using a range() loop. It's more readable and efficient.
for i in range(len(things)): do_something(i,things[i]) i = 0 for v in things: do_something(i,v) i += 1 for i,v in enumerate(things): do_something(i,v)5
u/fox_is_permanent Feb 08 '23
Yeah that's the actual use for
enumeratebut in what way can it help with duplicate values? I mean, how would duplicate values be a problem at all?Does this imply OP has been using
list.index? Because that's extremely inefficient as it's like running a nested for loop inside the main one./u/dangerlopez is that what you're referring to? If you need to replace the values of a list as you iterate you should always use
enumerate, not just when you have "duplicate values".1
u/dangerlopez Feb 15 '23
The reason I thought of them in the context of duplicates is because enumerate of an iterable will never have duplicate elements. I’ve been doing problems on HackerRank and a lot of my solutions would fail because I would implicitly assume that the list or string or whatever I was being given wouldn’t have duplicates. I can’t think of an exact example, but I can go and find one if it would help explain my thinking.
However, it sounds like there are better ways to deal with duplicates? Like I said I’m the op, im still learning so it’s pretty probable im not doing things in the best way. I’ll find an example and maybe someone can help me find a better way!
2
u/WhipsAndMarkovChains Data Scientist Feb 08 '23 edited Feb 08 '23
Yes that’s the point of enumerate, I know. My question was why is it being brought up in the context of duplicate values?
2
u/Xiji Feb 08 '23
Inexperience of misunderstanding would be my guess.
There are other methods or functions which are better suited to the task.
If you need to remove dupes, cast the collection to a set, if you need to count them, use a dictionary or collections.counter.
I would also like to mention that it isn't a good idea to mutate a collection while you are iterating through it.
2
u/dan4223 Feb 08 '23
The else clause for "for loops" is misnamed in my opinion. To me, logically the else clause should fire if the for loop doesn't finish.
2
u/dangerlopez Feb 08 '23
Yea I see what you’re saying. Maybe ‘finished’ would’ve been a better name, as in, when then loop is finished do this.
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)
15
8
6
u/porncornroz Feb 08 '23
Mate what editor do you use for writing markdown text?
It would be cherry on top if you maintain it using git
11
u/jimtk IdontChat Feb 08 '23
Currently I use VScode. Since I use Pycharm for most of my work, Vscode is available, free, fast to start and has a nice preview window. So I don't need to loose my train of though in Pycharm while I work on my cookbook and I can have both open simultaneously.
Edit: Extensions: Markdown all in one and Markdown Github Preview.
9
u/bythenumbers10 Feb 08 '23
I'm gonna recommend Obsidian. Handles lots of markdown files, tons of tools, can be maintained/synced between multiple devices in a number of ways (including Git). Fair warning, it's a rabbit hole, but it's replaced my other notebook software and has done so in an open-source, future-proof format, so I think it's worth it.
3
u/jimtk IdontChat Feb 08 '23
I tried Obsidian and fell in the rabbit hole of setups and plugins. When I finally got out of it I said to myself: "What a fantastic, well designed tool, I'm never gonna use it! Ever!"
But if it works for you, great.
3
u/bythenumbers10 Feb 08 '23
Understandable. I started with Evernote, back when they were free & unlimited & amazing. The web clipper & app made it a great second brain to store webcomics & whatever else. As they cut back, I made the mistake of switching to Zoho Notebook. I finally exported everything in html & while I lost the timestamps, I still have all my notes & clippings organized in markdown, so it's basically future-proof.
But I agree, it requires picking up new habits. Once you start in a good system, it's hard to stop!!
2
u/GrayLiterature Feb 09 '23
I’m going to recommend Neovim, specifically, the Telekasten plug-in. It’s essentially Obsidian in Neovim, so while you’re coding and working on things you can, with no friction, copy code and place it in your linked notes.
I used Obsidian and VS Code for a long time, but what I realized is there is a lot of time spent between the thing I want to do and my time to do do it.
I can now go from coding, to copy pasting some code, to a new note in about 5-7 keystrokes. It drastically reduces the friction for me to write notes.
1
u/bythenumbers10 Feb 09 '23
That sounds cool. I've been considering making a "cookbook", it's popped up here from time to time, and having it integrated into my editor would be pretty cool. I'll have to look into Neovim!!
1
Feb 09 '23
I really like VSCode for it personally, but often I'll just do it in GitHub itself. The GitHub MD editor isn't as nice, but it has the benefit of 100% guaranteed showing you what people looking at your repo will see.
1
u/Ran4 Feb 09 '23
I use Vim (or the neovim fork). It's definitely worth the time to learn it as it's possible to be SO much more productive when editing text.
Though the learning curve is a bit steep so I generally wouldn't suggest learning it while you're also learning basic programming. But as an intermediate level programmer (knows the syntax, can write a 100 line program from beginning to end...) it's definitely something you should consider learning.
Just like playing an instrument, very few people regret learning vim.
5
Feb 08 '23
Could you share this holy bible you have curated over time? :)
19
u/jimtk IdontChat Feb 08 '23
There are a few reasons why I don't share it.
It's personal. Not in the sens of privacy, in the sens that it contains what I need and what I encountered. There's nothing on game programming, there's a good chunk on Pyside, a lot of the little things I tend to forget (slicing use cases) and a good chunk on os.walk, listdir and the like because every 6 months I have to write a new file management script and I forgot everything I did 6 months ago!
It's not that big, because I regularly delete stuff from it. For example pathlib used to be in it. I've now used pathlib so much I've "integrated it". I don't need it anymore. So It's gone.
There are a lot of more or less related tidbits in it. Did you known that on Windoze there's a py launcher and that the command
py -0pwill give you a list of all the pythons version installed on the system (and their path). SO I would have to clean those up.It's work and responsibility. Publishing, even just on github, is a certain responsibility. I would have to Git that thing, maintain it, some people would cry when I delete something, or cry when their favorite thing is not in there. I just don't want to maintain that.
It defeats the purpose. Making my cookbook is what makes the tips and tricks get in my brain. The process of maintaining it is more important that the document itself. You have to make your own to really profit from it.
tl;dr: I'm lazy.
2
Feb 08 '23
Makes sense. Thanks for the tidbits on how you curate this book. Especially the part where once things are "integrated" into foundations....its omitted from the book. Cheers :)
3
u/jimtk IdontChat Feb 08 '23
Other than my last point (5), I think this is the most important. You don't want to end-up with a large, unwieldy document that takes time to load, and forever to find what you're looking for. If you need an index or a table of content, it's too big.
I also keep one on my Linux machine about linux. Because everything is a trick or tip on linux!
1
u/notislant Feb 08 '23
^ For me as well, for my private cheat sheets I post things I know ill likely forget and I put what will likely be incomprehensible gibberish to anyone else, what I did. But it'll immediately cover the part I personally will forget.
2
u/Guideon72 Feb 09 '23
brilliant...I've been holding firmly on to list[::-1] from, basically, day one. I'm stealing the rest of these, though.
How useful it will be in the long run is debatable so far, but onto this one just in case:
only alphumeric input: ''.join(filter(str.isalnum, str)).lower()
Useful if you want to quickly compare or create a new, "clean" string from random user input.
3
u/jimtk IdontChat Feb 09 '23
Oh! You will see that
lst[:-n]andlst[n:]are used fairly often (mainly with n=1).Also, I'm part of a strong religious group that wants to see
filterandmapremoved from the python language. :)So:
s = input("Enter alphanum string: ") s = ''.join(c.lower() for c in s if c.isalnum()) print(s)2
1
1
u/zeebrow Feb 08 '23
I started a markdown file of my own way too late, store it in Gittea. 10/10 would recommend.
But recently I started using and IDE more. Turns out logging format strings are in the
Formatterclass doc string, so all I have to do is ctrl right-click :)1
u/rickyy_cr2 Feb 08 '23
This is a great idea, actually. I’m going to start doing this but a bit differently. I work in data science/analysis so we use Jupyter notebook quite a bit. Jupyter gives you the ability to write code and run it in a single cell while also using markdown for notes.
2
u/JoSevlad Feb 08 '23
For Obsidian app there is a plugin that enables Jupyter for markdown code blocks and makes code in them runnable.
1
u/rickyy_cr2 Feb 08 '23
I’ve never heard of Obsidian before. I just checked it out and looks like a fantastic tool. Thanks for sharing!
1
1
1
1
26
u/Fun_Independent_7529 Feb 08 '23
I can't even remember where I ran across it first, but learning that python has it's own Counter I didn't learn for awhile. I had always been looping through content creating my own dictionary.
https://realpython.com/python-counter/
It's not always what you need, but if you are just taking some input and creating a dictionary to work from, it's using C under the covers and is faster.
21
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Feb 08 '23
A few of my personal favourites would be:
pathlib- it's simply a game changer for anything involving the filesystem and/or reading from/writing to files no matter where they are. Cross-platform. With minimal boilerplate. Honestly my favourite part of the entire standard library, it's simply a joy to work with every time.Did you know you can tell Python to raise another exception when handling one, as a built-in syntax feature? Me neither, until about a year ago when I stumbled across it in the docs by pure chance.
try: 4 / 0 except ZeroDivisionError as err: raise ValueError from errI mean, okay, it's not something you'd use every day, but surely we can agree it's pretty cool.
itercan accept a secondary argument, which basically lets you repeatedly call a function or other callable until it returns a value equal to the second argument. It can be very nice to know when code golfing, because it enables one-line while-loops, including infinite ones.sum(iter(lambda: print("Hi") or 0, 1337))This last one is obvious to us more experienced developers, but for beginners it might look like magic; all operators are just method calls.
Instead of writing
print((6 + 5 * 4 - 3) // 2)we could technically write
print(int.__floordiv__(int.__sub__(int.__add__(6, int.__mul__(5, 4), 3), 2)))and it would not only be perfectly valid Python, but would give the same result. Of course, no sane dev would do this, but it's a great demonstration of how Python's object model works under the hood.
7
Feb 08 '23 edited Feb 08 '23
Did you know you can tell Python to raise another exception when handling one, as a built-in syntax feature? Me neither, until about a year ago when I stumbled across it in the docs by pure chance.
It's PEP 3134!
In recent Python versions, the default behavior is almost exactly the same as this so it isn't really worth doing.
Only
from Noneis really different.Examples using 3.11. I seem to remember this came in in 3.9?
Without
fromtry: raise ValueError('a') except Exception as e: raise TypeError('b') Traceback (most recent call last): File "/code/test/python/exception.py", line 3, in main raise ValueError('a') ValueError: a During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/code/test/python/exception.py", line 8, in <module> main() File "/code/test/python/exception.py", line 5, in main raise TypeError('b) TypeError: bWith
from e:try: raise ValueError('a') except Exception as e: raise TypeError('b') from e Traceback (most recent call last): File "/code/test/python/exception.py", line 3, in main raise ValueError('a') ValueError: a The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/code/test/python/exception.py", line 8, in <module> main() File "/code/test/python/exception.py", line 5, in main raise TypeError('b') from e TypeError: bSo the only practical difference between these two is line 11!, a single changed line of not-very-interesting error.
But with
from None, it's a different matter:try: raise ValueError('a') except Exception as e: raise TypeError('b') from None File "/code/test/python/exception.py", line 8, in <module> main() File "/code/test/python/exception.py", line 5, in main raise TypeError('b') from None TypeError: bYou only get one stack trace, not two.
You can even do
raise e from None- not quite the same as justraisebecause it edits out all the intermediate frames...This is something I do occasionally when I have something like SQLAlchemy with very deep stack traces, and I want to report the exception but omit all those levels
Finally, Python 3.11 generalizes this idea to "exception groups", which I haven't used yet. There's a good explanation here https://realpython.com/python311-new-features/ and it also goes into "exception notes" which I also haven't used, and zero-cost exceptions, which I suppose I'm using all the time without knowing it. :-)
3
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Feb 08 '23
Well, looks like I learnt something new today. Just more proof that this subreddit is a metaphorical goldmine!
I do read the "what's new" articles for every version, but I'm sure everyone is bound to miss something every once in a while. I'm also the scatterbrain type, so unless I actually take genuine interest in something and give it a go I'll most likely forget it, or at least the details, shortly after reading about it.
2
u/Iongler Feb 08 '23
Thank you for this!
I found nr 4 especially interesting, looks almost like lisp.
1
u/POGtastic itertools evangelist Feb 08 '23
#4 can be useful when doing higher-order functions. For example, consider the dictionary merge operator
|.>>> dct = {"foo" : "bar", "baz" : "quux"} >>> dct2 = {1 : 2, 3 : 4} >>> dct | dct2 {'foo': 'bar', 'baz': 'quux', 1: 2, 3: 4}Suppose that we want to merge an iterable of dictionaries. And yes, it's probably more Pythonic to do
result = {} for dct in iterable: result |= dctBut I like higher-order functions, and
dict.__or__ends up being the reducer of choice.from functools import reduce # ... result = reduce(dict.__or__, iterable, {})1
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Feb 08 '23
It can indeed, although generally speaking I prefer to just use
operatorfor clarity.from functools import reduce from operator import or_ ... result = reduce(or_, iterable, {})It generally results in better readability.
8
u/commy2 Feb 08 '23
The optional argument of next.
3
u/DigThatData Feb 08 '23
ref https://docs.python.org/3/library/functions.html#next
the optional argument is a default return value to use if the iterator is exhausted
8
u/DigThatData Feb 08 '23
the @property decorator, which let's you define class attributes that are lazily evaluated or even computed on the fly
4
Feb 08 '23
Upvote for a fave decorator.
What I use a lot these days is
@cached_property, like this:from functools import cached_property class MyClass: @cached_property def massive_list(self): return some_huge_computation()
.massive_listacts like a property, but it's only computed once, and only the first time it's called, so if I don't use it, I don't pay for it.The interesting thing is that it even works with immutable classes, for example classes decorated with
@dataclass(frozen=True), because it directly operates onself.__dict__.
7
7
u/shinitakunai Feb 08 '23
List comprehensions to filter simple lists or dicts.
us_data = [x for x in mylist if x.startswith("US")]4
Feb 08 '23
There are also dict comprehensions:
inverse = {i: i * i for i in range(8)}and set comprehensions:
lower = {c for c in string if c.islower()}Also, generators can be more efficient than list comprehensions:
us_data = [x for x in mylist if x.startswith("US")] # mylist might be huge # perhaps: us_data = (x for x in mylist if x.startswith("US")) # nothing is evaluated yet return next(us_data) # Returns the first value it finds, doesn't visit the rest.1
u/DigThatData Feb 08 '23
i like that
return next(...)trick, much more elegant than what I usually do: convert it to a for loop andbreakout of the loop after finding what I'm looking for.
6
u/FantasticEmu Feb 08 '23
I’m not too bright. I’ve never found an explanation of enumerate that I can understand
9
u/synthphreak Feb 08 '23
Here’s the ELI5.
Given the list …
foo = ["a", "b", "c"]… let’s say you use a “regular” for loop:
for item in foo: print(item)This gives you access to each item. Cool.
But what if I want to reference each item’s index too, not just the item itself?
Well, you could use
list.index:for item in foo: index = foo.index(item) print(item, index)But this won’t work in every case.
So instead, you could just maintain a counter:
index = 0 for item in foo: print(item, index) index += 1But that’s kinda clunky and a lot to type.
You could also iterate over an array of indices instead of
foodirectly:for index in range(len(foo)): item = foo[index] print(item, index)But this is a lot to type too. Plus you’d need to index into
footo access the item, which is kind of a pain.So what to do?
enumerateto the rescue!for index, item in enumerate(foo): print(item, index)In just one line, you can assign both the index and the item to their own variables, leading to nicer code.
So
enumeratedoesn’t allow you to do things you couldn’t already do without it. Instead, it just makes your code cleaner, more readable, and more Pythonic.And that’s all there is to it.
5
1
u/Frankelstner Feb 08 '23
for i in range(len(data)): v = data[i]is (usually) equivalent to
for i,v in enumerate(data):It's about clearly specifying your iteration variables right at the top instead of hiding them inside the code block below. This assumes that the loop does need
ibecause otherwise we would just iterate over data directly without enumerate.1
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Feb 08 '23
Whenever I don't understand something, what usually helps is looking at code that implements the same feature.
At one point I made it a habit to rewrite some of Python's built-in functions myself,
enumeratebeing one of them.All it really boils down to is a for-loop and a counter that defaults to starting from zero:
from typing import Generator, Iterable, T, Tuple def my_enumerate(iterable: Iterable[T], start: int=0) -> Generator[Tuple[int, T], None, None]: idx = start for value in iterable: yield idx, value idx += 1If you prefer a version without type hints,
def my_enumerate(iterable, start=0): idx = start for value in iterable: yield idx, value idx += 11
Feb 09 '23
for i, v in enumerate(my_list): ...is the same functionally as
for i in range(len(my_list)): v = my_list[i] ....It's for when you need to keep track of what index you're on in a list. It's preferable to the second example because it's much easier to read and harder to make mistakes with. In Python, you generally shouldn't ever iterate over a list by incrementing an index. You can pretty much do a search for "
range(len(...))" in your code and replace it with enumerate. I treat it as a code smell.1
u/Guideon72 Feb 11 '23
It allows you an iterator that allows you to easily retrieve the index and item of a list, for example. I've mostly used it to format/display menus or bullet lists. Has an optional argument for controlling the display of index number.
menu = ["Option 1". "Option 2", "Option 3"] for idx, item in enumerate(menu, 1): print(F'{idx}: {item}') returns 1: Option 1 2: Option 2 3: Option 3
4
u/porncornroz Feb 08 '23
Man every comment in this thread is just pure gold. Incredibly informative and you just know I have been learning for more than a year.
4
u/ArchipelagoMind Feb 08 '23
I've been coding for about five years. I learned the enumerate method last week...
I'm like... bordering on angry I didn't know.
1
u/Free_Blueberry_695 Feb 09 '23
I'm like... bordering on angry I didn't know.
I don't laugh at Reddit comments very often but this did it for me.
3
u/battier Feb 08 '23
Glad you mentioned this because I was thinking of doing the same thing! I thought it would make for good mobile reading.
3
u/theRIAA Feb 08 '23
⌚ timestamp/datestamp
import time
timestamp = time.strftime('%Y%m%d-%H%M%S')➕ append line to txt file
with open("test.txt", "a") as myfile:
myfile.write("appended text")🖇 Conditional expression / ternary operator
result = "yep" if my-var == 1 else "nah"
#nested
result = "a == b" if a == b else "a > b" if a > b else "b > a"🎺beep
import chime
chime.theme('big-sur')
chime.success()and lots more where that came from
My python work has gotten a little easier after I started saving quick snippets like this. I just leave that Logseq sidebar up when coding as a paste area/journal, and it can also show that snippet page. I have more helper-pages for lots of languages/apps.
2
2
u/Crypt0Nihilist Feb 08 '23
Else clauses on loops
I didn't know this existed, have never needed it and am positive I'll now have to use it tomorrow.
1
u/Natural-Permission Feb 08 '23
From where are you learning python since beginning? Tutorials? or some coding camps etc.? I'm interested in learning as well but I don't know anything about programming etc. I'm totally zero on these things but want to learn..
1
u/metaphorm Feb 08 '23
list comprehensions are ridiculously convenient. it's just syntactic sugar, but it is sweet sugar indeed.
1
u/thegainsfairy Feb 08 '23 edited Feb 08 '23
any time I have to do something weird computationally in python, I look for these kinds of features. Because they've probably thought of it and its really readable
I particularly like the self documenting object literals for fstrings: https://docs.python.org/3/whatsnew/3.8.html#bpo-36817-whatsnew
>>>user = 'eric_idle'
>>>member_since = date(1975, 7, 31)
>>>f'{user=} {member_since=}'
"user='eric_idle' member_since=datetime.date(1975, 7, 31)"1
u/notislant Feb 08 '23
Make sure you join The Odin Projects discord. The help channels will save you a lot of time. Still best to try and exhaust google and your own abilities first though.
1
u/greb88 Feb 09 '23
Hearty +1 to enumerate! Embarrassingly I only just learnt about this. No more x + 1 in my for loops.
1
u/SA302 Feb 09 '23
The tutorial is amazing, and well worth revisiting for any beginner who has put their time in to feel somewhat proficient, it will make so much more sense.
1
Feb 09 '23
Else clauses on loops: Too many times I used and abused Booleans to decide if a loop had terminated or not, but no more!
While I use this occasionally, I find the setting/checking a flag is much more readable. I think I prefer it, personally.
1
u/AhmadAlwadi Feb 09 '23
Lambdas, I mean sure I had used them before in uni projects, but, after 5 years of python, a new professor explained it in the most elegant way possible and my brain literally went like "oh"
1
u/Guideon72 Feb 11 '23
Can you share? :p I can make *use* of them in some cases, but it's still really only by 'brute force'...I struggle to do more than parrot the syntax where I think it might work and hope for the best outcome. Which, obviously, leads to a lot of time debugging ;(
1
u/AhmadAlwadi Feb 12 '23
not sure if i can do it justice but here we go
it is effectively a small function in a singular line that does one thing, very vague explanation i know, but some examples may broaden your understanding.
initially, the syntax, lambda args : return something based on the args
e.g.1 here is a scenario, i would like to get the square root of a number, but i want it to be dynamic, like i want to be able to calculate that square root for more than one number, so a function is the way to go, following are the two ways i can do it
01- a regular function:
def getSqrt(x): return math.sqrt(x)
and then i can call that function just like any other function
02- use lambdas
getSqrt = lambda x : math.sqrt(x)
and i again can call sqrt just like any other function and it would give me the same answer
in the previous example, lambdas purpose was exclusively aesthetic, but here follows a more helpful example
e.g.2 i would like to sort a list of strings by the second letter of each element
using lambdas:
l = sorted (mylist, key = lambda x : x[1])
the above line does exactly what i want, sort a given list, mylist, by the second letter of each element, breaking it down: lambda takes each element of the list, and stores it in a variable called x, then it returns the second character of x, then the sorted function takes that returned value and sorts the list based on that input. the good thing about using lambda here is it doesn't care about what its taking as input, i maybe want to sort a list of lists, or a dictionary, or a list of floating point numbers, it doesn't care, it takes an input and returns the second element in said input.
out of scope: if my program was based on oop and i had an object and i wanted to sort a list of instances based on a specific attribute of that object, say the age of a person for example, i can still use lambdas, it would look something like this:
sortedInstances = sorted(instances, lambda x : x.age)
i just love lambdas, they're incredibly versatile and they look quite neat and make me feel smart
p.s. if you struggled with any term i used i am happy to explain it further
1
u/TheRNGuy Feb 09 '23
Knew about enumerate but not else after loop.
Don't have any uses for else after loop though.
1
u/Guideon72 Feb 11 '23 edited Feb 11 '23
pathlib has been mentioned a few times in this thread, but I want to call out a particular usage that I wish I had known earlier on.
Being able to create a file path relative to the file being run, instead of attempting to rely on .cwd or passing strings is really nice.
from pathlib import Path
basedir = Path(__file__).parent
path = basedir / "data"Plus, pathlib makes it stupidly easy to create files/folders if they don't already exist. So, there's no good reason to hobble yourself by manually creating files and using strings to define the paths getting started.
15
u/eleqtriq Feb 08 '23
Medium.com has a lot of little tid-bit tip articles for Python. Lots of click-baity "You should know these 10 ten" type of things about Python. Silly, but sometimes I find stuff or libs I didn't know about.