4 ms·
DO NOT replace [:] with list() next time you see it. While the article explains some concepts well, [:] is no less pythonic than list(), though the latter migh
by anuraggoel 18y ago
DO NOT replace [:] with list() next time you see it.
While the article explains some concepts well, [:] is no less pythonic than list(), though the latter might be more readable for people completely new to the language. In fact, it would be helpful to become very comfortable with python slices early on, because they allow you to easily manipulate any sequence, not just lists. For example, you can reverse a string using slices in one line:
reversed_string = orig_string[::-1]
Staying away from slices, you're leaving that power behind.
- marcus 18y agoAnother neat trick with slices is that you can do a partial update on a list. a = range(6) a[::2] = range(10,13) -> generates a with [10,1,11,3,12,5] I saw a very elegant implementation of Eratosthenes sieve based on that trick
- d0mine 18y agohttp://www.rosettacode.org/wiki/Sieve_of_Eratosthenes#Using_numpy http://www.rosettacode.org/wiki/Sieve_of_Eratosthenes#Using_... from numpy import bool_, nonzero, ones def primes_upto(limit): is_prime = ones(limit, dtype=bool_) for n in xrange(2, int(limit**0.5) + 1): if is_prime[n]: is_prime[n*n::n] = 0 return nonzero(is_prime)[0][2:]
- diN0bot 18y agothis starts to become as cryptic as the previously mentioned 'cryptic regex.' cryptic is anything that can stay in the head 'ram' of a normal programmer. stuff that typically needs to be written down to make sense. i went through the above code with pencil and paper and it made sense. now i can look at the code and it makes sense. the person who originally wrote the code had to go through those steps too (not necessarily on paper, but loading the process into head ram). same with regex. no big deal. i know about slices, and if i didn't that's what mentors are for---oh, that symbol? search for python slices! or a python book. at least python doesn't has less than a handful nonsearchable crypticness. the comment linking to the eratosthenes sieving explanation was helpful.
- d0mine 18y agoSieve of Eratosthenes is actually a straightforward algorithm based on the definition of prime numbers: 1. Mark all integers that greater than 1 as primes. 2. Take the smallest prime that is not already considered and cross out all its multiples. 3. Repeat 2nd step for the next prime. The above Python code that returns all primes number less than a given limit uses two optimization: 1. Repeat 2nd step upto sqrt(limit), not upto limit. 2. Start crossing out at the square of the prime, not at twice of the prime. The only “intuitive” interface is the nipple. After that, it’s all learned. http://news.ycombinator.com/item?id=409288 http://news.ycombinator.com/item?id=409288 (It might be not true literally but the quote is useful as a general idea that people have different backgrounds; an “intuitive” thing for one person is a cryptic for another. Intuitiveness changes with experience.)
- Harkins 18y agoAs this thread mentions cryptic code, Perl, regexps, and primes, I'm compelled to paste the cryptic Perl regexp to determine primes: /^1?$|^(11+?)\1+$/
- d0mine 18y agoIt is not cryptic it is just wrong. '1' is not a prime number. See my answer http://news.ycombinator.com/item?id=479514 http://news.ycombinator.com/item?id=479514
- palish 18y agoProgramming shouldn't contain 'neat tricks'. (Incidentally, one of Python's guiding principles is "explicit is better than implicit": http://www.python.org/dev/peps/pep-0020/ http://www.python.org/dev/peps/pep-0020/) Every single instance of "reversed_string = orig_string[::-1]" should be preceded with a comment saying "reverse the string", because it's not immediately obvious what [::-1] does. You can learn what it does, but it's not obvious, the same way a cryptic regex isn't obvious. So why not write reversed_string = orig_string.reverse()? (Or reverse( orig_string ) if that's more Pythonic.)
- deleted 18y ago[deleted]
- dood 18y agoBut [:] and [::-1] are not neat tricks, they're basic features of the language, and are immediately understandable once you've learnt about slices. Practically the opposite of a cryptic regex. The purpose of comments should not be teaching the reader the language, that just makes the code noisy.
- jpd 18y agoBut regular expressions are not neat tricks, they're basic features of Perl, and are immediately understandable once you've learned about them.
- dood 18y agoAre you suggesting that a cryptic regex is as easy to read as [:] or [::-1]? If you know python, that syntax is clear at a glance, dense regular expressions are not comparable. Basic language features don't need comments, difficult to read lines do.
- thwarted 18y agoAnd that depends on if regular expressions are a basic language feature. The proper way to "explain" or "comment" a complex regular expression is not to include a single line comment near it, but to use the /x modifier that allows you to "extend your pattern’s legibility by permitting whitespace and comments". That is, of course, assuming you're using a language where regular expressions are first class types and has syntax to support regular expressions as literals (if you have to include your regular expression in a quoted string, your language doesn't), and uses PCRE.
- henryprecheur 18y agoreversed_list = list(reversed(orig_list)) This works too, and IS more readable. But this doesn't work for a string for example. I didn't stay to replace ALL slices with list(). Of course this wont work all the time. For instance [:] has nice properties like conserving the sequence type: >>> (1, 2, 3)[:] (1, 2, 3) >>> [1, 2, 3][:] [1, 2, 3] This is not possible if you call list(), or tuple() directly. Slice is a feature that requires more "cleverness" from the programmer and more brain power from the guy reading the code. To cite Dijkstra: "[The competent programmer] avoids clever tricks like the plague." If list() make your code clearer, use it. The goal is to write a working program with clear and readable code, not to show off with you mastery of slices.
- anewaccountname 18y agoGive me one example where you would ever want a copy of a tuple rather than another reference to it.
- henryprecheur 18y agoThat wasn't my point. My point was that [:] conserves the type of sequence. Also [:] returns a reference to the existing tuple instead of a copy: >>> a = (1, 2, 3) >>> id(a) 3081276268L >>> id(a[:]) 3081276268L
- d0mine 18y agonumpy arrays do not copy on `[:]` therefore an explicit `.copy()` is required. `copy.copy()` makes a shallow copy of both a ordinary list and numpy arrays.