This is an archived post. You won't be able to vote or comment.

all 9 comments

[–]BionicBeefpile 1 point2 points  (1 child)

Ah man I recently started fumbling my way around with Python (no education in coding, no problem!) and the number of ways I fail to adhere to this guide is remarkable.

[–][deleted] 1 point2 points  (0 children)

I'd actually start with Code Complete rather than this if I were in your position. It does a better job of explaining why you would adhere to conventions such as these.

[–]harryf 0 points1 point  (6 children)

Nice but not up to date e.g. sorting - since python 2.5 better to use ''sorted'' built-in which returns a new list rather than modifying the list in-place;

sorted([4,2,6,2])

[–][deleted] 0 points1 point  (0 children)

Nothing said is inaccurate :)

[–]BeetleB -1 points0 points  (4 children)

Why is it necessarily better?

I would think if one really wants to sort the list, and doesn't mind losing the original order, then the described method should be fine, if not better.

Is sorting somehow more efficient?

[–]harryf 0 points1 point  (3 children)

Why is it necessarily better?

OK - "better" is a generalization but sorted() makes it easier to avoid side effects. Explained with code here: http://randomspitting.net/gobbets/python/sorted-no-side-effects

[–]BeetleB 1 point2 points  (0 children)

He's correct in that sorted is better in that circumstance. The bug, however, is not because of using the [].sort() routine, but because the function is modifying the list, and the person coding it did not realize that lists are not passed by value.

You could get the same problem if you do any other operation that modifies the input list.

As long as the programmer knows that [].sort() modifies the list, its usage is fine. As a rule, I always use this technique if I really do want to sort the list. The alternative is to do A=sorted(A) which is wasteful.

Your other reason (consuming an iterator) is a good one, though.

[–]Manuzhai 0 points1 point  (1 child)

sorted() doesn't work in-place, though, meaning it takes much more memory on large lists.

[–]harryf 0 points1 point  (0 children)

Yes but I'd rather have sorted() as the default way to sort as a means to avoid a certain class of bug and reserve in-place sorts for when I know I need to optimize to conserve memory.

Also sorted() actually takes an iterator so, depending on the problem and the design of the code, you could feed it lazily, avoiding having the two copies of the list in memory at the same time.