Hey man, just finished my first website thanks to your flask tutorial. Thank you for taking your time and experience and sharing it with us so that we can learn!
Using a default dict in the mentioned case is not really pythonic either, since there is a counter in the collections module. The code would then become: from collections import Counter numbers = [ ... ] c = Counter(numbers) the Counter API offers a lot of additional functionality and is generally to be preferred over the default dict. The default dict should be used when there is some additional work to do on insertion, like it was done in the second case. Regarding the context manager: If you catch yourself writing many try-finally blocks, that is normally the moment to use one. You can also implement custom managers for your own classes via the dunder methods `__enter__` and `__exit__`. Those are what is executed by the with statement: with Foo(args) as bar: baz() more or less desugars to bar = Foo.__enter__(args) try: baz() finally: Foo.__exit__()
6:25 I think that is better to use the class Counter (from collections as well), which does the exact same as defaultdict, but you don't have to do any for loop. >> form collections import Counter >> counter = Counter([1, 2, 3, 4, 1, 4, 4, 1, 4, 3, 3, 2]) >> counter Counter({4: 4, 1: 3, 3: 3, 2: 2}) >> conter = dict(counter) >> counter {1: 3, 2: 2, 3: 3, 4: 4} Nice video
good beginner tips, couple comments: - the mutable args is not a bad practice, it's a bug because the code won't work as intended, the usual way to deal with that is to default to None and then check to assign the mutable object - the defaultdict is a good tip but if you're counting there's an even more specialized object class Counter that you can use - `with open()` works because open() can be used in that fashion but not all classes do, there's a helper called closing() in the contextlib module that helps with that cases
For the number count one you can also use: counts = dict.fromkeys(set(numbers), 0) for key in numbers: counts[key] += 1 (although this requires the numbers to be created before the dict, and its not so easily updatable, but still an ok method)
In the first example I think of the parameters being passed 'by reference' versus 'by value'. Whats interesting is that the mutable parameter has a lifetime that is not limited to a single call of the function which we would expect for a local variable in the function. Instead the mutable parameter stays in memory and is acting like a static class variable. We could print the memory location of the mutable parameter to see that this is the case.
Excellent video. We often learn about what is a "pythonic" way of doing something without an explanation on the reasons behind it, is it a slight difference in performance like with defaultdict and enum, or can bad and unexpected things happen.
Hi Tim. I love your videos. They have helped me endlessly. But one thing I'd like to call out, is that you use names that are too similar to built-in words, such as "list", "string", and "dict" which may make things very confusing to people who are new to programming (e.g. "Why does he say 'string +='??"). I'd suggest writing things like "the_list", "new_string", or "my_dict" so that people are more likely to understand that these are custom variables, arguments/parameters, or objects, rather than built-in words that may throw errors when they try to write a program that uses things like "str", "list", and "dict" (etc). Thanks again and I hope you have a great weekend!
Oh gosh. And this comment is super ironic because your last section is not overriding built-in keywords! (which you spelled "keyboards" in your lower-3rd btw)
I don’t understand your first explaination. - Why a string is not mutable ? What does mutable exactly mean ? From my instinct the problem should be exactly the same for a list and for a string. - To make the comparison more fair either both the string and list should be empty or both should be not empty. Here i don’t know if the problem comes from the fact that the list is a list or from the fact that the list is empty. - You don’t give any workaround. What should i type instead of “number=[]” in order to return the desired list ?
For the fourth bad practice I heard that often, that you shouldn't use range. But I don't see a workaround when you need to modify any list as directly looping through the list you cannot set new variables to old values
knew a good pprtion of these but now its time to go refactor some code for those mutable default params... whoops. need more of these videos! great job!
`defaultdict(lambda: 0)` should be replaced with `defaultdict(int)` imo also id, zip, and list are not built-in keywords, rather they're built-in functions
For the defaultdict section, would the following code also be appropriate: counts = {} numers = [1, 2, 3, 1, 6, 4, 1, 3, 9, 8, 2, 6, 8,4, 5 ,7[ for key in numbers: counts.setdefault(key, 0) count[key] += 1 or is that the equivalent of checking: if key not in counts: counts[key] = 0 counts[key] += 1
Could you give me an advice? Because I don't know what I can do. I'm immediately advanced and I want to make a big project but I can't. It's just too hard. And now I don't know how to get to the higher level. How I can improve my skills without watching next tutorial? Should I practise more? Could you help and recommend something? Thanks.
# Mutable Default Parameter: The bad practice here is not having a mutable default parameter: it's actually *mutating* the default parameter in the function body which is bad. # Not Using A Default Dict: TLDR: Not using defaultdict isn't a bad practice, though not using it in *this specific example* might be, and it is definitely use-case dependent. Not using a defaultdict is not a bad practice, though it may be in this specific scenario. The demonstrated use-case is a good use of defaultdict. Some scenarios may require that the program take a different flow if a key does not exist. I'll use the way Flask handles request parameters as an example for this: If a Flask endpoint attempts to access a parameter that does not exist, the parameter dictionary will raise a KeyError. Flask then catches this exception to automatically return a 400 Bad Request response, since a required parameter is missing from the request. This behavior is good, and emulating the same behavior with a defaultdict would require extra checks from the developer, which is exactly what we're trying to avoid in Tim's example. # The Last Three: 100% agreed
for i, val in enumerate(list):. Well, that's crazy. How does anyone know the first variable, called i, in this case is the index. If the statement were written with the following variable names, for value_of_x, value in enumerate (list):, then the index is value_of_x variable. How could anyone know the first variable in the index variable in the for loop?
@@Zancb If u go through python docs, there it is written that one _ at beginning makes a variable non public but that doesn't mean it is private, do try that in code take example of inheritence u will understand difference b/w private(__) and protected(_).
@@roxx2k356 "Not public" is another way of saying "private". Stop trying to protect your ego by talking around the facts. Double leading underscores are usually used for mangling class variables to avoid naming collisions when someone does "from module import *" Single leading underscores keeps the variables from a class/import from being readily accessible (in other words PRIVATE). Stop needlessly arguing because you're so desperate to be "correct". You're wrong. Move on.
@@Zancb Bro, i don't have any ego i just said what i read from lot of sources, anyways they can be wrong but can u explain then how to declare protected variables in python, cause it seems u know some other way around or u are not considering protected variables are a thing in python..??
Hey can you make a video going through collections, abc and data structures in python. Can anyone explain why sometimes, python will reorder my lists if I’m dealing with large collections on the fly. Furthermore, sometimes I feel I’m battling against python to keep a data type. Forcing me to apply unnecessary type hints and conversions 24/7.
I think the first one is a really bad feature, why does it have to mantain the link to the same location even when the function ends? It is breaking the local scope logic, I don't get the reason
Why is that first one even a thing? If I want to be tormented by non-obvious details of the language I’m using, I’d just stick with C++ or JavaScript. At least Python still has more good than bad compared to other common languages.
@@ultimatejy9393 you are rigth, i have never used the function so i asume it returned d[k] but returns its value, so yeah your initial code is rigth, sorry about that
For all my fellow class XII students, always remember that the 'return' keyword brings the said object/iterable back to your main program, i.e- "return List" will create a list called 'List', containing whatever variables the function has filled it with.
An attribute that is 'locked' inside, encapsulated within a class. Meaning it is only used within the class, it cannot be inherited or used outside of the class
Can't know how I stopmed onto this. Anyway Damn good video 🙌🙌. I also have been watching those rather similar from MStarTutorials and kinda wonder how you guys make these clips. MStar Tutorials also had amazing info about similiar things on his vids.
Dear person whoever reads this, Hey, you, yes, I am talking right to you. I hope you will see yourself with the eyes I see you one day, because I can tell you have some awesome music taste :) You’re such a beautiful human being and worth and enough. I hope you know that you do only need yourself to be happy, I know society build up the standard that whenever you’re alone you’re not living a happy live. But in fact that is not true, if you start to realize that you actually deserve all the good things happening to you, you will treat yourself a lot nicer. I hope you let yourself rest, don’t beat yourself up over past mistakes, over regret, and over everything your mind wants to destroy you. I wish I could remove all those demons inside of your head because you deserve to feel happy. If you ever feel lonely then watch the sky, because you know, someone, at the same time is watching the sky too, maybe feeling the same way..I am glad you exist and I hope you won’t ever remove your own spot in this world, maybe you don’t feel like you belong here but, Angel, then build your home here. I don’t want you to leave this world unhappy. I want you to live every little second, I want you to feel alive, I don’t want you to see yourself just existing. You deserve it. Whatever happened, it’s not your fault, the demons in your head recognize that you have a beautiful heart, they want to take it because they have never seen such beautiful heart as yours, so why let them win over you? . You’re not selfish for isolating yourself, but you deserve to talk to someone. If you’re reading this than please never forget to breath and smile. Don’t live up to other standards! It’s your story and not theirs. Life for those who couldn’t, smile for those who forgot what a genuine smile is, love like there’s no other, hug like it’s your last one. I love you and send you hugs. You’re so strong, you’re still here, and I am proud of you. YOU ARE NOT USELESS. READ THAT AGAIN. Enough with beating up yourself for today, okay?! - The stranger that cares about you more than anything. I hope this is enough for you to stay today, tomorrow will be a new day, a new start, let go now. I hope you can stay. This is your sign to stay and treat yourself with love, you deserve it. And in case no one told you today, again, I am so proud of you. I hope you will remember my words- :) Until tomorrow, my friend . Take care! :)
Hey man, just finished my first website thanks to your flask tutorial. Thank you for taking your time and experience and sharing it with us so that we can learn!
is it available for people to see or is it hosted locally on your computer?
@@mavdotj It is currently hosted locally as I still have not published it but in the next few hours il upload it to the web.
@@mateoortega4649 did you upload it?
How long did it take?
Can we have a look?
Using a default dict in the mentioned case is not really pythonic either, since there is a counter in the collections module. The code would then become:
from collections import Counter
numbers = [ ... ]
c = Counter(numbers)
the Counter API offers a lot of additional functionality and is generally to be preferred over the default dict. The default dict should be used when there is some additional work to do on insertion, like it was done in the second case.
Regarding the context manager: If you catch yourself writing many try-finally blocks, that is normally the moment to use one. You can also implement custom managers for your own classes via the dunder methods `__enter__` and `__exit__`. Those are what is executed by the with statement:
with Foo(args) as bar:
baz()
more or less desugars to
bar = Foo.__enter__(args)
try:
baz()
finally:
Foo.__exit__()
6:25 I think that is better to use the class Counter (from collections as well), which does the exact same as defaultdict, but you don't have to do any for loop.
>> form collections import Counter
>> counter = Counter([1, 2, 3, 4, 1, 4, 4, 1, 4, 3, 3, 2])
>> counter
Counter({4: 4, 1: 3, 3: 3, 2: 2})
>> conter = dict(counter)
>> counter
{1: 3, 2: 2, 3: 3, 4: 4}
Nice video
*from
good beginner tips, couple comments:
- the mutable args is not a bad practice, it's a bug because the code won't work as intended, the usual way to deal with that is to default to None and then check to assign the mutable object
- the defaultdict is a good tip but if you're counting there's an even more specialized object class Counter that you can use
- `with open()` works because open() can be used in that fashion but not all classes do, there's a helper called closing() in the contextlib module that helps with that cases
For the number count one you can also use:
counts = dict.fromkeys(set(numbers), 0)
for key in numbers:
counts[key] += 1
(although this requires the numbers to be created before the dict, and its not so easily updatable, but still an ok method)
Start @1:48
Tim literally drops a video everyday... Bless Up Man!!!
Alright someone is thinking about intermediate developers! Thanks Tim, these are really helpful!
17:25 don't override "keyboards"
OKAY
In the first example I think of the parameters being passed 'by reference' versus 'by value'. Whats interesting is that the mutable parameter has a lifetime that is not limited to a single call of the function which we would expect for a local variable in the function. Instead the mutable parameter stays in memory and is acting like a static class variable. We could print the memory location of the mutable parameter to see that this is the case.
Hello Tim.
Wow, 🤩 great content as always, thanks for sharing it!🙏🏻
I just loved it💜!
Excellent video. We often learn about what is a "pythonic" way of doing something without an explanation on the reasons behind it, is it a slight difference in performance like with defaultdict and enum, or can bad and unexpected things happen.
Hi Tim. I love your videos. They have helped me endlessly. But one thing I'd like to call out, is that you use names that are too similar to built-in words, such as "list", "string", and "dict" which may make things very confusing to people who are new to programming (e.g. "Why does he say 'string +='??").
I'd suggest writing things like "the_list", "new_string", or "my_dict" so that people are more likely to understand that these are custom variables, arguments/parameters, or objects, rather than built-in words that may throw errors when they try to write a program that uses things like "str", "list", and "dict" (etc).
Thanks again and I hope you have a great weekend!
Oh gosh. And this comment is super ironic because your last section is not overriding built-in keywords! (which you spelled "keyboards" in your lower-3rd btw)
I don’t understand your first explaination.
- Why a string is not mutable ? What does mutable exactly mean ? From my instinct the problem should be exactly the same for a list and for a string.
- To make the comparison more fair either both the string and list should be empty or both should be not empty. Here i don’t know if the problem comes from the fact that the list is a list or from the fact that the list is empty.
- You don’t give any workaround. What should i type instead of “number=[]” in order to return the desired list ?
For the fourth bad practice I heard that often, that you shouldn't use range. But I don't see a workaround when you need to modify any list as directly looping through the list you cannot set new variables to old values
try using list comprehension, i have tried a few examples and it was always faster than using a for loop
6:34 I guess a Counter class from collections module would be more appropriate for this case :)
yes
Learned something from reading comments!
knew a good pprtion of these but now its time to go refactor some code for those mutable default params... whoops.
need more of these videos! great job!
Hi Tim! What keyboard do you use? Are you happy with it or would you recommend something else for programming? Thanks!
Any keyboard will work
`defaultdict(lambda: 0)` should be replaced with `defaultdict(int)` imo
also id, zip, and list are not built-in keywords, rather they're built-in functions
6:24 for that I might just as well write
counts = {key: numbers.count(key) for key in set(numbers)}
Great vid, had no idea about setdefault, it's basically a defaultdict when you can't use imported modules.
Thanks
For the defaultdict section, would the following code also be appropriate:
counts = {}
numers = [1, 2, 3, 1, 6, 4, 1, 3, 9, 8, 2, 6, 8,4, 5 ,7[
for key in numbers:
counts.setdefault(key, 0)
count[key] += 1
or is that the equivalent of checking:
if key not in counts:
counts[key] = 0
counts[key] += 1
Why use default dict rather than using Counter from collections? Aren't they doing the same thing in this case?
Not sure.
Could you give me an advice? Because I don't know what I can do. I'm immediately advanced and I want to make a big project but I can't. It's just too hard. And now I don't know how to get to the higher level. How I can improve my skills without watching next tutorial?
Should I practise more? Could you help and recommend something? Thanks.
# Mutable Default Parameter:
The bad practice here is not having a mutable default parameter: it's actually *mutating* the default parameter in the function body which is bad.
# Not Using A Default Dict:
TLDR: Not using defaultdict isn't a bad practice, though not using it in *this specific example* might be, and it is definitely use-case dependent.
Not using a defaultdict is not a bad practice, though it may be in this specific scenario. The demonstrated use-case is a good use of defaultdict. Some scenarios may require that the program take a different flow if a key does not exist. I'll use the way Flask handles request parameters as an example for this: If a Flask endpoint attempts to access a parameter that does not exist, the parameter dictionary will raise a KeyError. Flask then catches this exception to automatically return a 400 Bad Request response, since a required parameter is missing from the request. This behavior is good, and emulating the same behavior with a defaultdict would require extra checks from the developer, which is exactly what we're trying to avoid in Tim's example.
# The Last Three: 100% agreed
that first one shows that python is freaking stupid at times
Five reason to use the code analysis (Linter) features in Pycharm.
One doesn't need to put a trailing underscore after id. It could be a hyphen or a numeral or another letter.
hypen will not work for minus it is
very insightful!! thank you @TechWithTim
just an Amazing video for ppl who are getting started with python!
previous video: "imports should always be in the top of your code"
this video: "line 10: from collections import defaultdict"
the solution to the first problem you have mentioned may be declare the mutable object to "None". E.g: "numbers = None
Thanks a lot for context manager
I understand the behavior of mutable default parameters, but am curious if this behavior is intentional? When would it be useful?
for i, val in enumerate(list):. Well, that's crazy. How does anyone know the first variable, called i, in this case is the index. If the statement were written with the following variable names,
for value_of_x, value in enumerate (list):, then the index is value_of_x variable. How could anyone know the first variable in the index variable in the for loop?
Very helpful, thanks!
The first one is something that happen to me and I didn't even know this sh*t 😑
Happened to me a couple of days ago.
Nice tutorial, Small correction in the last part i remember _var means protected variable, __var means private variable.
That's incorrect. Look at Python's documentation for naming variables and functions. The prepended underscore is for private variables.
@@Zancb If u go through python docs, there it is written that one _ at beginning makes a variable non public but that doesn't mean it is private, do try that in code take example of inheritence u will understand difference b/w private(__) and protected(_).
@@roxx2k356 "Not public" is another way of saying "private". Stop trying to protect your ego by talking around the facts.
Double leading underscores are usually used for mangling class variables to avoid naming collisions when someone does "from module import *"
Single leading underscores keeps the variables from a class/import from being readily accessible (in other words PRIVATE).
Stop needlessly arguing because you're so desperate to be "correct". You're wrong. Move on.
@@Zancb Bro, i don't have any ego i just said what i read from lot of sources, anyways they can be wrong but can u explain then how to declare protected variables in python, cause it seems u know some other way around or u are not considering protected variables are a thing in python..??
3:55 ...Aaah, I see you're a fellow Canadian eh?
Hey can you make a video going through collections, abc and data structures in python.
Can anyone explain why sometimes, python will reorder my lists if I’m dealing with large collections on the fly.
Furthermore, sometimes I feel I’m battling against python to keep a data type. Forcing me to apply unnecessary type hints and conversions 24/7.
Pls can u do a tutorial on KivyMD
I really love your intense algorithm
Thank you ❤️
Keep the good work
use Counter(list) for getting dictionary ... no need to write for loop
Oh my gawd I wish i knew about defaultdict years ago.
If he would tell us why an integer type is mutable, but a characteristic type is not, we could better understand why python works this way.
Hey can you please make a video on how to make a wordsearch game and algorithm
Didnt work on mine. Can you help me?
He said, "comma," but he typed a colon punctuation mark at 16:47.
I think the first one is a really bad feature, why does it have to mantain the link to the same location even when the function ends? It is breaking the local scope logic, I don't get the reason
Hello could I code with a 16gb ram, i5 10th gen and a nvida 3060 ?
Why is that first one even a thing? If I want to be tormented by non-obvious details of the language I’m using, I’d just stick with C++ or JavaScript. At least Python still has more good than bad compared to other common languages.
can I use setdefault in the word count example?
s = "hello"
d = {}
for k in s:
d.setdefault(k, 0)
d[k] += 1
print(d)
yes, you can use it like that but i think is more pythonic with d.setdefault(k,0) += 1, as setdefault already return the d[k]
@@mauro_carvajal i just tried your suggestion, it's not working. d.setdefault(k,0) actually return integer instead of the dict object
@@ultimatejy9393 you are rigth, i have never used the function so i asume it returned d[k] but returns its value, so yeah your initial code is rigth, sorry about that
@@mauro_carvajal it's ok... We are all on the path of learning 😊
May I know when will your minecraft server on discord be up?
Bro how did you learn python
Thanks 😊
which font is it?
7:38 subtitles, tee hee
For all my fellow class XII students, always remember that the 'return' keyword brings the said object/iterable back to your main program, i.e- "return List" will create a list called 'List', containing whatever variables the function has filled it with.
great video
How do you feel about using a private variable name with a mutable default parameter? I.e.
def some_dynamic_prog(x, _memo={}):
an argument should not have a private variable name
@@mauro_carvajal should dynamic programs always pass the initial data structure when called?
Am I the only one that got in the first "problem", the answer 1 [1] 2 [1,2] (like how it's printing) ? (I am kinda new to python)
You mean [1] are indexes or what
The infamous Stack Overflow blind copy paste FTW
18:09 from builtins import zip as realzip
Hahahahahaha
18:45 what does a private variable mean ?
An attribute that is 'locked' inside, encapsulated within a class. Meaning it is only used within the class, it cannot be inherited or used outside of the class
@@tornadol6530 oh I see thanks for the explanation
Great!
To the top
First mistake took me an hour to debug.
I didn't watch the whole or have anything funny to say so I wanna claim my early ticket so
I say we E
Thanks Thanks Thanks
People who do codewars daily might have known the second one ;)
Yo
Tim:
My Mind: my bad habits lead to late night bla bla bla.........
Best😍😍♥👊🏼
Why are you saying "zed" for the letter z lmfao, then 2 seconds later you say z as just "z"
"not a mutable object", "not immutable object", dude, english is so confusing, why do they need those dam articles?
Can't know how I stopmed onto this. Anyway Damn good video 🙌🙌. I also have been watching those rather similar from MStarTutorials and kinda wonder how you guys make these clips. MStar Tutorials also had amazing info about similiar things on his vids.
Aahh.. may I have a heart❤️ sir?
Of course!
One more free heart ❤
That mutable parameter thing is a poor language design thing.
first
Your views have gone way down buddy
What's your point?
First !!!
First?
Wow, you kids still do this? Fun.
@@Zancb wow u grandpa's still write this?
Dear person whoever reads this, Hey, you, yes, I am talking right to you. I hope you will see yourself with the eyes I see you one day, because I can tell you have some awesome music taste :) You’re such a beautiful human being and worth and enough. I hope you know that you do only need yourself to be happy, I know society build up the standard that whenever you’re alone you’re not living a happy live. But in fact that is not true, if you start to realize that you actually deserve all the good things happening to you, you will treat yourself a lot nicer. I hope you let yourself rest, don’t beat yourself up over past mistakes, over regret, and over everything your mind wants to destroy you. I wish I could remove all those demons inside of your head because you deserve to feel happy. If you ever feel lonely then watch the sky, because you know, someone, at the same time is watching the sky too, maybe feeling the same way..I am glad you exist and I hope you won’t ever remove your own spot in this world, maybe you don’t feel like you belong here but, Angel, then build your home here. I don’t want you to leave this world unhappy. I want you to live every little second, I want you to feel alive, I don’t want you to see yourself just existing. You deserve it. Whatever happened, it’s not your fault, the demons in your head recognize that you have a beautiful heart, they want to take it because they have never seen such beautiful heart as yours, so why let them win over you? . You’re not selfish for isolating yourself, but you deserve to talk to someone. If you’re reading this than please never forget to breath and smile.
Don’t live up to other standards! It’s your story and not theirs.
Life for those who couldn’t, smile for those who forgot what a genuine smile is, love like there’s no other, hug like it’s your last one.
I love you and send you hugs.
You’re so strong, you’re still here, and I am proud of you.
YOU ARE NOT USELESS. READ THAT AGAIN.
Enough with beating up yourself for today, okay?! - The stranger that cares about you more than anything. I hope this is enough for you to stay today, tomorrow will be a new day, a new start, let go now. I hope you can stay. This is your sign to stay and treat yourself with love, you deserve it.
And in case no one told you today, again, I am so proud of you. I
hope you will remember my words- :)
Until tomorrow, my friend . Take care! :)
No. 1 Do not program in Python
No. 2 Repeat step No.1
python is cool
@@ixypsylongaming Skateboards are cool but I wouldn't use them on a motorway.
@@ertagon You can do various stuff with python
@@ixypsylongaming And that's the problem, because no one ever stops to ask if they should.
public class SunEkaLuokka {
public static void Main(string[] args) {
System.out.println("Mitä jäbä leissaa?")
}
}
Python is a garbage language. The company i work in only has C++ programmers. Maybe we don't know something in this world? Hahah.
And there you go. Python is an unsafe language for serious software engineering.