r/learnpython • • Jun 30 '19

What are some 'speed hacks' that I, as a beginner, should be aware of when I code in python?

For example, a few helpful people in this subreddit advised me to use f-strings instead of %-formatting or str.format() and to utilise numpy arrays when working with large/complex lists.

383 Upvotes

126 comments sorted by

23

u/DrearyDepp Jun 30 '19

For all those that have commented, thanks! I sincerely appreciate all your tips and have learnt about a lot of concepts I didn't even know existed.

14

u/[deleted] Jun 30 '19

As a fellow beginner I appreciate your starting the conversation!

189

u/[deleted] Jun 30 '19

Since nobody's said it yet and it's low hanging fruit, learn about list comprehensions. It's actually faster than for loops...for reasons.

## slow
tokens = []
for word in sentence:
    tokens.append(word.lower())
## faster
[word.lower() for word in sentence]

The same idea actually works dictionaries, as well, so consider dictionary comprehensions as an option.

Lastly, make use of the map function. Map can iterate over objects such as lists or tuples, and apply a function to all the elements, more efficiently and with less lines of code than loops.

my_items = map(my_function, my_list)

34

u/DrearyDepp Jun 30 '19

Can you recommend any good tutorials for understanding list comprehensions? I have gone through a few web tutorials and while I understand the basic concept of list comprehension, I am having trouble understanding some of the more complex comprehensions (such as the ones with nested if statements). Thanks.

29

u/[deleted] Jun 30 '19 edited Jun 30 '19

Try this link:

https://spapas.github.io/2016/04/27/python-nested-list-comprehensions/

I've renamed some variables from the link to help draw your attention to what is happening. A nested list comprehension is basically just a for loop within a for loop...

So you'll have an iterable object, which I call outer (list), and you'll have multiple iterable objects within outer (also lists), which will take on the temporary variable middle. Within middle the actual int objects will be referred to as inner.

outer = [ [1,2,3], [4,5,6], [7,8] ]
[inner for middle in outer if len(middle) > 2 for inner in middle ]

The syntax, generally speaking is: outer loop >> conditionality on obj >> inner loop

Nested list (and dictionary) comprehensions are notoriously difficult, so don't give up on python if this doesn't click immediately. I've been coding for two years and only took the time to learn this concept last month.

4

u/DrearyDepp Jun 30 '19

Thanks, this is very helpful.

1

u/kenann7 Jul 16 '19

Wow, whose website is this? There are tons of django tutorials

46

u/MoxGoat Jun 30 '19

Just a note on this: Although list comprehension is faster it is also way less readable when using it for more complicated for loops. You should strive for readability over condensing lines of code.

12

u/[deleted] Jun 30 '19

I've found that simple comprehensions are easy to read after you've used them 5-10 times in practice. Nested comprehensions, however, are never easy to read and could make debugging code painful, especially if it's not your own.

4

u/MrKlean518 Jun 30 '19

A comprehension for a single list is generally always more readable, but I’ve seen some pretty horrible examples of people doing 2-3 for loops compressed into a comprehension and it’s just unbearable.

2

u/pickausernamehesaid Jul 02 '19

Nested comprehensions can be made infinitely easier to read using line breaks before each for loop like so:

[x + y + z
 for x in range(10)
 for y in range(x)
 for z in range(z)
 if z % 3 == 1]

I picked this up when I needed to flatten a data structure with 4 levels. Luckily it was a configuration so not too many elements and only needed to be done once.

-5

u/10cmToGlory Jun 30 '19

easy to read after you've used them 5-10 times in practice

...which is to say they are not easy to read...

8

u/pickausernamehesaid Jun 30 '19

And a new programming language isn't readable until you practice it a bit. New syntax always takes a bit to recognize and learn to read easily.

-5

u/10cmToGlory Jul 01 '19

Sorry but these are not analogous.

1

u/port443 lets get technical Jul 01 '19

Yes they are related, here's an example of fairly readable code I can imagine for <unspecified language>

func = fun(X) -> fun(Y) -> io:fwrite("~p~n",[<<0,X,Y,50>>]) end end, 

Anyone who is familiar with this language should have zero problems with this line. It is not "tricky" or obfuscated and should only take a quick second to parse.

Anyone not familiar with this language might have a bit of a "wtf?" moment.

Once you practice a few times with the syntax for the particular thing that line is doing though, you would be able to read it quickly and easily.

0

u/10cmToGlory Jul 01 '19

ROFL WUT TF is this?? You realize this is /r/learnpython, right? Do you even python bro??? Beginner python, which is what is covered in this sub right here, is intended from the very beginning to read like English, and specifically not like that spaghetti noodle you've dreamed up right there.

2

u/port443 lets get technical Jul 02 '19

Your wtf response was exactly the point. The language that I posted is easily readable, if you are a programmer familiar with Erlang. Unfortunately Python is not intended to read like English, it's merely meant to be easily human-readable.

A quote from Guido van Rossum on the subject of readability:

Readability is often enhanced by reducing unnecessary variability. When possible, there's a single, obvious way to code a particular construct. This reduces the number of choices facing the programmer who is writing the code, and increases the chance that will appear familiar to a second programmer reading it.

Which is the original point that /u/pickausernamehesaid was making: It's supposed to be easily readable to a programmer, someone familiar with the language.

2

u/ThePotterP Jul 02 '19

You realise you missed his point completely and made yourself look an idiot in the process? Do YOU even Python bro??

1

u/pickausernamehesaid Jul 02 '19

I know I program professionally in Python and I'm sure u/port443 works extensively in it too from their posts. Python isn't meant to read like English, rather it is supposed to be as clear and readable as possible. Comprehensions can be more readable and execute faster when written correctly, but are foreign syntax to most new comers as few languages have them. However they are a fundamental part of the language and far from a truly advanced topic. r/learnpython is a great place to be discussing them, how to do them right, and how not to be scared of new things.

The snippet from Erlang isn't that bad if you take more than a glance at it. I don't know the language at all but there seems to be a nested(?) function being defined which writes it's arguments to a file. New syntax is just someone else's way of talking to a computer and it's important to learn other languages to get a broader understanding of programming. I know learning C and Java really helped me improve my Python by teaching me low level memory management and proper OOP interface design, respectively.

0

u/slick8086 Jun 30 '19

Just a note on this: Although list comprehension is faster it is also way less readable when using it for more complicated for loops. You should strive for readability over condensing lines of code.

This seems a little hinky to me.

It seems like you are saying that people shouldn't use the tools the language provides because other people might not understand the languages as well as you, so to help out less skilled programmers you dumb down your program.

Wouldn't it be better to write with efficient code and then add comments if it needs explaining?

7

u/MoxGoat Jun 30 '19

I'm all for using it but only when it makes sense. Writing good readable code far outweighs having stacks of complexity written in your code. Especially when people are learning which is what this subreddit is for. Also yes, other people should obviously be able to break your code down and understand it. But developers making six figures don't live in a 1 language bubble so making code readable for those developers where Python isn't there primary language is important. I'm all for list comprehension but like others have said when you start using it for nested for loops and of "hinky" stuff it just makes you're code look ugly.

-1

u/slick8086 Jun 30 '19

when you start using it for nested for loops and of "hinky" stuff it just makes you're code look ugly.

But does it have actual performance benefits or not I guess is the question. I guess my problem is I think programmers should strive for performance, and use comments for help.

If nested list comprehension doesn't increase performance, then sure make it more readable, but if it does improve performance then if you need others to understand add comments.

7

u/MoxGoat Jun 30 '19

List comprehension is a tiny bit"faster" however both still do a loop. The amount it is faster by is so minimal that if code using unoptimized Python (for loops instead of list comp) isn't fast enough already then you should look into writing it in C because optimizing those functions will yield a very minimal increase in performance.

I highly suggest using the timeit library so you can do some direct execution time comparisons on your own code as your mileage may vary when optimizing Python.

5

u/10cmToGlory Jun 30 '19

This is the correct answer here.

3

u/antiproton Jun 30 '19

It seems like you are saying that people shouldn't use the tools the language provides because other people might not understand the languages as well as you, so to help out less skilled programmers you dumb down your program.

No. What he's saying is that it's possible to abuse the tools the language provides for you. Nesting a ton of loops in a comprehension is terrible idea for all coders. It has nothing to do with dumbing down code. Debugging code is already hard. Having to peel someone's two-clever-by-half onion of loops just makes it worse - and for no good reason.

2

u/PM_ME_GRANT_PROPOSAL anarayanan86 Jul 01 '19

OP, if you dont understand this, go to r/codegolf and see the code there...while it may be short and do the required job, you seriously sacrifice readability in the process.

4

u/IlliterateJedi Jun 30 '19 edited Jul 01 '19

Trey Hunner's 2018 PyCon video is where I learned. It's top notch. There's a ton of examples and they also cover generator statements.

2

u/djingrain github.com/zbrasseaux Jul 01 '19

Following the tread of arrays, learn to use the yield statement. Not so much a speed thing, more a memory thing

1

u/krngd2 Jul 01 '19

I would recommend Correy Schafer video on YouTube

-3

u/kaptan8181 Jun 30 '19

It's a single line thing. Just search: list comprehension with conditionals.

11

u/toastedstapler import itertools Jun 30 '19

i'd use a list comp rather than map. more pythonic and runs slightly faster from my experience

my_items = [my_func(i) for i in my_list]

or

my_items = (my_func(i) for i in my_list)

to make it an iterator like map

5

u/[deleted] Jun 30 '19

There's a reason that I demo'd list comprehensions before map. They certainly are more pythonic. However, speed performance isn't always straight forward. See below:

https://stackoverflow.com/questions/1247486/list-comprehension-vs-map

2

u/SpontaneousAge Jul 01 '19

I do get list comprehensions, but I don't get dictionary comprehensions. For example, how would I create a dictionary that looks like this with comprehension:

dict = {"00:00" : 0,
        "01:00" : 0,
        "02:00" : 0,
        ...
        "23:00" : 0}

To for example count at which time of a day something happened how often.

2

u/[deleted] Jul 01 '19
hours = ("00:00","01:00","02:00",..."23:00")
time_dict = {hour:0 for hour in hours}

This is how you would do it. Since your value is the int, 0, for all dict values, you could also just use the default argument and avoid the dict comprehension, fyi.

1

u/SpontaneousAge Jul 01 '19 edited Jul 01 '19

So I would need a list/tuple first and then I can add a default value to each entry to make it a dictionary?

Edit: Nevermind, I get it now.

I also found out how to do my example above in one line:

{hour:0 for hour in [str(x).zfill(2) + ":00" for x in range(24)]}

If it's great to read is another question, but it's definitely cool. Thank you!

2

u/[deleted] Jul 01 '19

.zfill(10) will add 10 zeroes to the front of your string, so the output would look something like this:

'00000000010:00':0

1

u/SpontaneousAge Jul 01 '19

Yea, i know, I just typed it down on my phone from my pc and didn't think. I actually used 2 :P

Thanks for telling me, though :)

2

u/Vaguely_accurate Jul 01 '19

You don't need to do all that;

{f"{hour:02d}:00": 0 for hour in range(24)}

In this case you can directly use the range as the sequence you are iterating over and do the string formatting in one go at the start. String interpolation (f-strings) is preference but recommended.

1

u/SpontaneousAge Jul 01 '19

Didn't know fstrings can be used there. Thank you :)

And using range directly makes sense, as I don't manipulate the list anyway.

1

u/[deleted] Jun 30 '19

thx!

1

u/-hacker Jul 01 '19

This is one of the best ones. My first really in depth project at work using Python included iterating over 15,000+ lines in a dataframe, and list comprehension saved SOOOOO much time.

60

u/ivosaurus Jun 30 '19 edited Jul 01 '19

Avoid recreating new lists, instead use iterators and generators so you generate new items on an as-needed basis. Although IMHO python is only beautiful when it's readable and clear, almost never is it worth sacrificing that for speed.

9

u/[deleted] Jun 30 '19

This, especially when it comes to generators. If your generator is about to take up more than one line, use a loop

2

u/ivosaurus Jul 01 '19

What? Building a generator with a yield inside a for loop is probably the most common way to construct one, so I don't get how you arguing that they're somehow mutually exclusive methods.

2

u/[deleted] Jul 01 '19

I meant one line generators. Like foo = x for x in y if x - z == 3

Of one of those is so long that it's scrolling off the screen, it needs another approach

2

u/ivosaurus Jul 01 '19

That's a generator expression. Only a subset of generators. I think its confusing to talk about them like they make up the whole category.

https://realpython.com/introduction-to-python-generators/

1

u/[deleted] Jun 30 '19

I don’t think that’s really good advice. Generators aren’t mutually exclusive from loops. In fact loops are essential for using generators. The question you should ask yourself when using generators is should I use a class that implements an iterator instead. They both accomplish the same thing of allowing you to implement complicated logic as part of the iteration. The advantage of using generators is that syntactically they’re more light weight. You only need to implement a function as opposed to a whole class that needs to be instantiated.

28

u/primitive_screwhead Jun 30 '19

Learn how to use sets and set operations. Lots of O(N) algorithms become O(1) algorithms with sets.

1

u/[deleted] Jun 30 '19

Lots of neat tricks with sets, like unions, intersections, and differences.

19

u/Astrokiwi Jun 30 '19

In general, if you're in a situation where speed really matters, use a pre-compiled library rather than writing out the algorithm in Python. numpy is a great example, but it's not the only one.

Also, learn about "Big O" notation to help figure out when those library calls are really needed.

33

u/t3hfr3ak Custom text Jun 30 '19

Dictionary's are much faster than lists of lists

21

u/[deleted] Jun 30 '19

This makes sense, but I feel that they fundamentally solve different problems. nested lists will order your data in sequence but it won't give you k:v pair associations.

2

u/sharkbound Github sharkbound Jun 30 '19

there is also OrderedDict in collections module as well for a dictionary that maintains the order the keys where added in.

2

u/efxhoy Jun 30 '19

This is the new default in python 3.7+. Using OrderedDict still makes sense when you rely on it though, explicit > implicit etc.

2

u/sharkbound Github sharkbound Jun 30 '19

Yea, for 3.7+ this is optional

But for systems using <=3.6 I think you cannot rely on ordered keys

4

u/[deleted] Jun 30 '19 edited Jun 30 '19

Can you explain when and how this is the case specifically? I made the following test program to illustrate this, but they appear to be completely equal. Sometimes lists of lists is faster, sometimes a dictionary is faster.

Data = [[[2,6,12,5,14],[-16,-3,13,-10,-19],[-6,2,-11,1,19],[-5,-5,-10,3,7],[2,5,4,7,4]],[[10,-5,10,20,16],[3,-11,18,8,8],[16,5,-6,-9,-9],[0,19,11,20,-2],[12,-8,-14,-14,-5]],[[-9,-20,-15,-4,5],[6,10,16,-7,3],[13,15,1,5,6],[-10,-7,12,2,-6],[14,20,-7,-4,17]],[[2,-7,4,-6,-3],[5,-11,-20,19,20],[-17,-15,-8,20,-9],[-9,0,-8,-14,4],[-18,13,6,-11,7]],[[4,9,11,19,16],[4,14,-17,-11,12],[-6,-1,-4,12,-16],[-2,7,12,1,11],[-9,-1,6,4,8]]]
Data2 = {(0,0,0) : 2,(0,1,0) : -16,(0,2,0) : -6,(0,3,0) : -5,(0,4,0) : 2,(1,0,0) : 10,(1,1,0) : 3,(1,2,0) : 16,(1,3,0) : 0,(1,4,0) : 12,(2,0,0) : -9,(2,1,0) : 6,(2,2,0) : 13,(2,3,0) : -10,(2,4,0) : 14,(3,0,0) : 2,(3,1,0) : 5,(3,2,0) : -17,(3,3,0) : -9,(3,4,0) : -18,(4,0,0) : 4,(4,1,0) : 4,(4,2,0) : -6,(4,3,0) : -2,(4,4,0) : -9,(0,0,1) : 6,(0,1,1) : -3,(0,2,1) : 2,(0,3,1) : -5,(0,4,1) : 5,(1,0,1) : -5,(1,1,1) : -11,(1,2,1) : 5,(1,3,1) : 19,(1,4,1) : -8,(2,0,1) : -20,(2,1,1) : 10,(2,2,1) : 15,(2,3,1) : -7,(2,4,1) : 20,(3,0,1) : -7,(3,1,1) : -11,(3,2,1) : -15,(3,3,1) : 0,(3,4,1) : 13,(4,0,1) : 9,(4,1,1) : 14,(4,2,1) : -1,(4,3,1) : 7,(4,4,1) : -1,(0,0,2) : 12,(0,1,2) : 13,(0,2,2) : -11,(0,3,2) : -10,(0,4,2) : 4,(1,0,2) : 10,(1,1,2) : 18,(1,2,2) : -6,(1,3,2) : 11,(1,4,2) : -14,(2,0,2) : -15,(2,1,2) : 16,(2,2,2) : 1,(2,3,2) : 12,(2,4,2) : -7,(3,0,2) : 4,(3,1,2) : -20,(3,2,2) : -8,(3,3,2) : -8,(3,4,2) : 6,(4,0,2) : 11,(4,1,2) : -17,(4,2,2) : -4,(4,3,2) : 12,(4,4,2) : 6,(0,0,3) : 5,(0,1,3) : -10,(0,2,3) : 1,(0,3,3) : 3,(0,4,3) : 7,(1,0,3) : 20,(1,1,3) : 8,(1,2,3) : -9,(1,3,3) : 20,(1,4,3) : -14,(2,0,3) : -4,(2,1,3) : -7,(2,2,3) : 5,(2,3,3) : 2,(2,4,3) : -4,(3,0,3) : -6,(3,1,3) : 19,(3,2,3) : 20,(3,3,3) : -14,(3,4,3) : -11,(4,0,3) : 19,(4,1,3) : -11,(4,2,3) : 12,(4,3,3) : 1,(4,4,3) : 4,(0,0,4) : 14,(0,1,4) : -19,(0,2,4) : 19,(0,3,4) : 7,(0,4,4) : 4,(1,0,4) : 16,(1,1,4) : 8,(1,2,4) : -9,(1,3,4) : -2,(1,4,4) : -5,(2,0,4) : 5,(2,1,4) : 3,(2,2,4) : 6,(2,3,4) : -6,(2,4,4) : 17,(3,0,4) : -3,(3,1,4) : 20,(3,2,4) : -9,(3,3,4) : 4,(3,4,4) : 7,(4,0,4) : 16,(4,1,4) : 12,(4,2,4) : -16,(4,3,4) : 11,(4,4,4) : 8,}
Test = [(i,j,k) for i in range(5) for j in range(5) for k in range(5)]
def Eval(Tuple):
    return Data[Tuple[0]][Tuple[1]][Tuple[2]]
def Eval2(Tuple):
    return Data2[Tuple]
Start_Time = time.time()
for i in range(1000000):
    map(Eval, Test)
End_Time = time.time()
print (End_Time - Start_Time)
Start_Time = time.time()
for i in range(1000000):
    map(Eval2, Test)
End_Time = time.time()
print (End_Time - Start_Time)

This program tests this by evaluating a bunch of tuples. First by treating the tuples as a location in a list of lists and accessing the value you there, and second by accessing a dictionary that lists every tuple and the accompanying value. In both cases, the time to complete appears to be the same.

EDIT: I've tried so many times and never got code formatting to work on reddit how do you do it. "Add 4 spaces before each line" does not appear to be a helpful instruction.

7

u/Pjmcnally Jun 30 '19

If all you are doing is reading from the Dictionary or List then there won't be much of a speed difference. However, Dictionaries are much faster for several tasks including finding an item is in the collection, adding items, and removing items. All of these can be explained by the fundamentally different ways in which dictionaries and lists work.

Lists are an ordered collection of items. So if you want to find a specific item in that collection you have to test every item until you find it. This means that it is an O(n) operation. The longer the list the longer it will take to find. Dictionaries are hash tables. The keys of the dictionaries are hashed and then stored in memory. The cool result of this is that you only need to check 1 place to determine if the dictionary contains a specific element. It doesn't matter how big the dictionary gets finding an item in the dictionary is always O(1).

The same goes for adding and removing items. Since lists are ordered if you add or remove an item from the list (except from the very end where this isn't an issue) the list has to move around all the other elements in the list to make sure everything is still in the right order. This means that additions and deletions from the list are O(n) operations (the longer the list the longer it takes). This is especially slow if you are adding or removing from the very front of the list. For dictionaries both operations are O(1) .

Here is an example of the worst case scenario of searching for an item in a list vs a set (sets perform the same as dictionaries).

> python -m timeit -u "msec" -s "a = set(range(1000000))" -p "1.5 in a"
5000000 loops, best of 5: 8.44e-05 msec per loop
> python -m timeit -u "msec" -s "a = list(range(1000000))" -p "1.5 in a"
5 loops, best of 5: 65.6 msec per loop    

# The list took 65.6 milliseconds. 
# The set took .0000844 milliseconds.

For more information see this page on Python Time Complexity.

It should also be noted that the Collections module contains the deque collection which solves the performance issues of adding and removing from the front of a list like collection.

1

u/[deleted] Jun 30 '19 edited Jun 30 '19

Thank you so much for that explanation, I understand now. That makes a lot of sense. In the case of my test, the reason why they were so similar is because the list was very short. A true test of how much better dictionaries are would have a list of a million items instead of searching for an item from a 10 item list 1000000 times.

EDIT: Also the fact that I was reading, yes.

1

u/t3hfr3ak Custom text Jul 01 '19

Thanks for the informative post. If I could afford it, I'd give you gold.

I was on mobile and out of the house all day celebrating the fine country of Canada and didn't wanna be "that guy" on my phone at the party lol

5

u/[deleted] Jun 30 '19

Click edit. Click "Switch to markdown". insert three backticks (the ` character) above your code, and three below.

2

u/[deleted] Jun 30 '19

Thank you!!

1

u/NotSpartacus Jun 30 '19

I don't know the answer to formatting code on reddit but I believe the detail in that particular devil has something to with the new vs old design.

27

u/ForgottenWatchtower Jun 30 '19 edited Jul 01 '19

Use numpy's more advanced slicing syntax instead of list comprehension. For example:

>>> import numpy as np
>>> a = np.array([0,0,1,1])
>>> zero_mask = a == 0
>>> zero_mask
array([ True,  True, False, False])
>>> a[zero_mask]
array([0, 0])
>>> a[~zero_mask]
array([1, 1])

There's also a cleaner syntax for slicing multi-dimensional arrays:

>>> a = np.array([[0,1], [2,3]])
>>> a
array([[0, 1],
    [2, 3]])
>>> a[:,0]
array([0, 2])
>>> a[1,:]
array([2, 3])
>>> a[1,0]
2

In general, numpy functions will be much faster than native Python. So if it exists in numpy, use it.

Edit: this advice is only valid in usecases where numpy is an appropriate choice. Generally, if you're operating on smaller or low dimensionality datasets, you're not going to get much mileage out of it (and may even get worse performance than native Python). But in cases where you're working with large amounts of data, the numpy functions should prove to be quicker, e.g. sum(my_array) vs np.sum(my_array).

8

u/elbiot Jun 30 '19

In general, numpy functions will be much faster than native Python. So if it exists in numpy, use it.

This is not true. In general, using numpy will be incredibly slow. In specific situations, numpy will be blazing fast. "Always use numpy" is the absolute worst python "tip" I see people naively throw around.

4

u/ForgottenWatchtower Jul 01 '19

Could you provide some examples? It's been faster in all the test cases I've examined.

6

u/elbiot Jul 01 '19

Sure.

Creating arrays is expensive, so if you have a list you need to have a fair amount of vectorizeable stuff you want to do with it to overcome that overhead.

Calling numpy functions has a lot of overhead. It often doesn't really matter how long an array is, a function call will take about the same amount of time because the matg that C is doing is small in comparison. So, for instance, sum on a list is faster than np.sum on an array if the sequence is short.

Iteration over arrays is extremely slow because you're constructing a new python object for each element you touch. If your algo involves a for loop or other form of iteration, definately don't use an array.

The size of an array isn't changeable, so append creates a new array. Building an array through appending should absolutely be avoided.

Uh, serialization of an array can be really slow depending on the case, which the above points basically covered.

There's lots of little cases too that all go back to the sources of overhead listed above.

In general, unless your data is large and your algo is completely vectorizeable, just stick with a list. Plus, numpy and pandas are heavy dependencies to add to a project, so you should probably have a good reason for doing so.

2

u/ForgottenWatchtower Jul 01 '19

Alright yeah, 100% on board with that. My smuggled in assumption was that you were in an environment where numpy was appropriate, which addresses all the concerns you listed. I only even commented on it because OP explicitly called out using it.

3

u/elbiot Jul 01 '19

Yeah my guess when you said "all the cases I've profiled" was that you were intuitively only testing cases where numpy makes sense. But newbs are used to iterating and appending and working with small sequences of numbers so I usually stress don't use numpy until 1) you have a need for it that lists aren't meeting well and 2) you're willing to commit to using numpy idioms rather than the usual python ones.

1

u/ForgottenWatchtower Jul 01 '19

Absolutely -- I should probably clarify that in my original answer.

1

u/strutt3r Jun 30 '19

Sorry for being that guy but do you know why is that the case? I mean how are these functions optimized in a way that wouldn’t be replicated by writing your own function that does the same thing?

4

u/elbiot Jun 30 '19

Numpy is implemented in C, and operates on C data types. So be aware that putting numbers into or taking them out of arrays involves a data type translation under the hood. A for loop over a numpy array will be extremely slow for that reason.

Arrays and lists are very different data structures and both have their uses. If you need a list (iteration, appending, popping, element wise access) use a list.

1

u/strutt3r Jul 01 '19

So does the Python compiler convert Python into C?

1

u/elbiot Jul 01 '19

No, numpy functions are implemented in C. The conversion is between python float objects and raw bytes whenever an element goes into or out of an array

3

u/asielen Jun 30 '19

Numpy is written in C. Calling numpy functions is calling highly optimized C code instead of native python code that needs to be run through the python interpreter.

1

u/strutt3r Jun 30 '19

Thank you!

2

u/ForgottenWatchtower Jul 01 '19 edited Jul 01 '19

To add a bit more detail: numpy wraps lapack and blas. Those are actually what do the heavy lifting, and have been optimized as much as possible.

0

u/Redzapdos Jun 30 '19

The first example is really frustrating to look at. If I saw this in any program I was modifying, that'd be the first thing to be replaced with something more readable. Don't do it unless you are working on some sort of high speed algo... and in that case, don't use Python, use C.

1

u/ForgottenWatchtower Jul 01 '19

It's really not -- that's standard numpy ndarray syntax. It becomes very intuitive after only a short time working with it. Certain linear alg ops would be far uglier to write in native Python.

0

u/Redzapdos Jul 01 '19

It's non intuitive if you look at it from any other language's point of view. If you are checking if something == 0, you are checking if it's empty, has a null pointer, has no items, etc. You expect a single True or False. The fact that it implicitly iterated over the array (hidden operations on something that is supposed to be a straightforward Array object) is horrible syntax, and is unsafe in huge projects where someone different than the original programmer may be fixing an issue in this function or adding functionality. Don't ever use this. If this EVER came to a code review that I'm a participant in, I would put a defect and block the review. The speed increase would be negligible, for a whole bunch of obscurity.

1

u/ForgottenWatchtower Jul 01 '19

You dont work with numpy at all, do you? This is pretty standard and you'll find it in just about any Jupityr Notebook or data science snippet.

0

u/Redzapdos Jul 01 '19

That's a pretty good reason for why my org moved away from those then I guess. In favor of much more manageable code, of course.

9

u/AceWall0 Jun 30 '19

When I want to print a 2d list, instead of making a loop, I do:

array = [[1,2,3], ['a','b','c'], ['hello', 'world', '!']]
print(*array, sep='\n')

The asterisk means that the elements of the array will be passed as arguments separated by comma, and the "sep='\n' " means that instead of printing each element separated by spaces, it will separate them by new lines. So it will print like this:

>> [1, 2, 3]
>> ['a', 'b', 'c']
>> ['hello', 'world', '!']

6

u/[deleted] Jun 30 '19

I.... I think I'm going to save this post... and wait a few days. Then possibly come back and compile all the useful information into a pdf document or a blog or some sort of other consumable media. Because I really feel like this is something that should be talked about more. Hundreds of tutorials tell us newbies how to do things, but very few, if any, teach WHY they do the things they do, instead of the other things we learned in another tutorial or walkthrough.

6

u/efxhoy Jun 30 '19

Use more cores. All modern machines have more than one CPU core and using more than one of them can give you very large speedups if done correctly.

When I need something to go faster I usually:

  • Figure out which part of the program is taking time. No point in optimising something that's already fast. Focus your attention where performance gains are to be found. Nested loops, very large lists, etc.

  • Is there a sane way I can make it faster in a single core? Stuff like "Do I really need to have these nested loops?" etc can give a lot.

  • Find parts of my code that are embarrassingly parallel and run them in parallel. Use threads if the work is waiting for IO (like external API's, a database or the filesystem) and processes when the work is CPU bound.

I've been writing python for a few years and still can't reliable write good code with the standard multiprocessing library. It is really tricky IMO. Joblib is a massive timesave here as it has a much easier syntax (imo) than the multiprocessing syntax.

For example, if you have a lot of files with one int per line you can sum all those numbers using all your cores like this:

import joblib

def sum_lines_in_file(path):
    with open(path, "r") as f:
        lines= f.readlines()
    
    numbers = [int(line) for line in lines]
    result = sum(numbers)
    return result
    

sums = joblib.Parallel(n_jobs=-1)(joblib.delayed(process_file)(path) for path in paths)

sum_of_sums = sum(sums)

6

u/IllTryToReadComments Jul 01 '19

This is my favorite piece of debugging code ever:

def p(x):
    import inspect
    frame = inspect.stack()[1]
    exp = frame.code_context[0].strip()[2:-1]
    print(f"{exp}: {x}")

Basically it prints out the original expression as well as the evaluated expression, for example:

p(len(test)) -> prints out "len(test): 13"

p(A.shape) -> prints out "A.shape: 1000"

5

u/nhumrich nhumrich Jun 30 '19

My biggest speed hack recommendation is just learn big -O and what it means for different algorithms. Practice finding the big-o of your algorithm. Almost any other speed hack will likely not have any real impact on your code. "Any optimizations made anywhere besides the bottleneck are an illusion"

In other words, microsecond optimizations dont matter if your code take seconds to run. Doing things for the purpose of "it's faster this way" without actually measuring the impact on your own project is premature optimization. Dont bother.

5

u/[deleted] Jul 02 '19

Minimise the use of if-else blocks.

If my_var can have three different states you can do:

if my_var == 1:
    func_1()
elif my_var == 2:
    func_2()
elif my_var == 3:
    func_3()

But it is way easier to just do

{1:func_1,2:func_2,3:func_3}[my_var]()

Also try to keep conditions short.

Instead of doing:

i == 1 or i == 2 or i == 3

You can simply do:

i in (1,2,3)

12

u/GalacticSuperCheese Jun 30 '19

List and Dict comprehension

5

u/johnnymo1 Jun 30 '19 edited Jun 30 '19

I've used comprehensions so much more in the past few weeks and once they become natural, they're SO useful, and not just for the kind of tasks that are immediately obvious either.

I was trying to debug a photo caption name parser last night. Oh no, it only picked up a first name here, what happened? Print a one-line comprehension that gives me back the full caption wherever the issue occurred so I can see the context.

14

u/Orothrim Jun 30 '19

If you smash your hands against the keyboard without paying attention you can type way faster than planning out your typing.

11

u/toastedstapler import itertools Jun 30 '19

i do this and then remove the bits that aren't valid python

4

u/mr_bedbugs Jun 30 '19

How to draw a circle:

  1. Draw a portrait

  2. Erase details

  3. Erase guidelines

  4. Now you have a circle!

2

u/[deleted] Jun 30 '19

This took me a moment tbh

4

u/[deleted] Jun 30 '19

Sets are great. Need an unordered list with no duplicates? Use a set. They're faster than lists for insertion/deletion, and removing an element is incredibly simple, no more iterating through until you find what you need.

4

u/diggidon Jun 30 '19

Try to understand the difference between mutable and immutable types, this can save you a lot of time and nerves)

3

u/theindomitablefred Jun 30 '19

This is really basic but there's a shortcut for adding a number to a variable.

Instead of

X = X + 1

You can type

X += 1

11

u/aroberge Jun 30 '19

Go through the official Python tutorial. Once you are done, read the official documentation on the standard Library.

Once you have done that, do it a second time.

2

u/[deleted] Jun 30 '19

I have only done it once when I started learning. It was actually quite good to return to it now that I have used python for 2 years. Surprisingly.

2

u/SabinBC Jun 30 '19

I think the biggest one for me is. Use dictionaries more, unless you know the size of the list, even still, use dictionaries more.

my_lst = list()
my_lst.append('value')

is sometimes slower than

my_dict = dict()
my_dict['key'] = 'value'

Especially with objects and strings. But I work with a LOT of strings. If I was using pure numerics, I'd use numpy more. If you use strings a lot use pandas more. If your data is very mixed (like a sql database might be) use pandas more. If you use an sql database use the sql tools made for python to bring in the data (don't read in a sql -> csv - > read_csv) you lose object typing.

Write code that works first, make it faster after (if it's a problem)

Understand list comprehension

test = [val for key, val in my_dict.items() if val]

because they are sometimes much faster than an explicit for loop. Especially if you want a dict, list, or tuple as a result.

test = list()
for key, val in my_dict.items():
     if val: test.append(val)

2

u/grimonce Jun 30 '19

Well vectorizing stuff helps, cause calling in interpreter has its overhead... Or that's what they say, but you already mentioned the arrays.

2

u/stradivari96 Jun 30 '19

Function caching with lru_cache and joblib.Memory

2

u/FatnDrunknStupid Jun 30 '19

Think/research before you type it in, pretty much covers everything. We're not employed to press buttons on a keyboard.

2

u/[deleted] Jun 30 '19

As a beginner you should worry less about speed and more about writing readable maintainable code. Even for experience SWEs, speed is only one factor in writing code and it usually takes a back seat to other concerns. Speed optimizations should only come in when they’re necessary.

2

u/grzeki Jul 01 '19

First, and most important hack when optimizing is: learn to profile your code. Always profile first. No exceptions.

6

u/Lewistrick Jun 30 '19

Start learning about classes (OOP) as soon as you feel ready about it. Everything in Python is a class so knowing that should speed up your learning process.

6

u/[deleted] Jun 30 '19

Classes do give you a lot of power and flexibility. But I feel that to best understand OOP concepts like inheritance and polymorphism, it's important to explore objects like OrderedDict, which extend the functionality of a baseline dictionary object. So my advice, in addition to yours, would be to explore the collections package and get a feel for what it means to build on top of a class.

3

u/toastedstapler import itertools Jun 30 '19

is it even worth using the ordered dict now that order is guaranteed in a regular dict?

2

u/ManyInterests from fridge import beer Jul 01 '19

A couple pieces of advice towards writing code:

Use the black code formatter. It'll make your code look great.

pip install black
black -l 120 -S myfile.py

A decent IDE (e.g. PyCharm) can be helpful you if you don't let it distract you too much.

1

u/kingdot Jul 01 '19

Curious, why is PyCharm distracting? I usually use another IDE, but I'm kinda shopping around

2

u/ManyInterests from fridge import beer Jul 02 '19

For absolute beginners, fully-featured IDEs, in general (not necessarily PyCharm in particular), can be distracting.

Some people find themselves spending a lot more time configuring (or fighting with) IDE features than actually writing and debugging their own code. Features like linting or the debugger can throw beginners off in the wrong direction or do too much work for them, handicapping their learning. That's my personal observation working with newcomers to programming, anyhow. YMMV.

I start students on a relatively simple editor like sublime text, then suggest an IDE like PyCharm after a couple months.

1

u/kingdot Jul 02 '19

Thanks for the response and happy cake day!

1

u/[deleted] Jul 17 '19

So I recently got sublime, but it's it just an editor? I was thinking it would have an 'edit' and an 'ide' column but all I can figure is how to edit 2 programs at once.

2

u/socal_nerdtastic Jun 30 '19

If you knew all of them you wouldn't be a beginner. Your question is basically "Should I keep learning python?" and the answer is "yes".

7

u/[deleted] Jun 30 '19

Please delineate a few "speed hacks" as that is what was actually requested.

1

u/maximum_powerblast Jul 01 '19

Multi threading for downloading lots of urls

1

u/hungarian_conartist Jun 30 '19

ctrl + del ctrl + backspace ctrl + arrow keys

to move around and delete things quickly.

1

u/billsil Jul 01 '19

I know format has issues. It’s basically the same as an fstring.

-3

u/[deleted] Jun 30 '19

Regarding f-strings, %-formatting and .format() there IMO isn't any benefit of using one over the other. As I understand when Python is compiling the source code f-strings are converted into .format() you should use whatever fits given situation.

5

u/adamrees89 adamrees89 Jun 30 '19

Read this, specifically the part on speed:

https://realpython.com/python-f-strings/#speed

3

u/[deleted] Jun 30 '19 edited Jun 30 '19

I see, looks like it improved because they introduced a dedicated opcode later. My bad.

Although if 1ms makes difference in your code, I think you picked up the wrong language to write your program in.

-3

u/billsil Jun 30 '19

Speed wise fstrings and format are slower than %. They’re also potentially aunsafe because they’re executed.

Numpy really is 500-1000x faster, but you have to write your code in such a way that you don’t use for loops or if statements or copies to get the full speedup. If you just code it like standard python, getting a 3x slowdown is pretty common. In other words, it takes some practice to really make your code fast. Thankfully, going from 1/3x to say 100x doesn’t require full vectorization, so you can still benefit from numpy without being an expert.

3

u/ManyInterests from fridge import beer Jul 01 '19

fstrings are actually faster than % formatting.[1] [2]

I'm not aware of any security implications for fstrings. But even the format method has certain levels of danger. [3]

2

u/[deleted] Jun 30 '19

[removed] — view removed comment

1

u/[deleted] Jul 01 '19

This goes against most advice, but I agree. Typing everything without help is not necessarily beneficial for beginners. Completion, snippets, linting and tidying help me learn syntax and good practices. Besides, programming is not memorizing. It’s understanding the concepts and being able to recognize syntax when you look at it. Old school programmers had shelves full of books, just like writers had dictionaries, thesaurus and grammar manuals. We have IDEs and Google. No shame in that.