bslatkin / effectivepython

Effective Python: Second Edition — Source Code and Errata for the Book
https://effectivepython.com
2.2k stars 710 forks source link

Error on bottom of page 46 #64

Open JDoyleNYC opened 4 years ago

JDoyleNYC commented 4 years ago

Hi I think the odds and evens index assignment values in Item 12 on page 46 are incorrect. Book says


x = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'] odds = x[::2] evens = x[1::2] print(odds) print(evens)

['red', 'yellow', 'blue'] ['orange', 'green', 'purple']

Even numbers being 0, 2, 4, wouldn't the expression used for odds x[::2] start at 0 index (red) and select every other one, i.e. index values at 0, 2, 4 being red, yellow and blue which are the even index values?

Same logic applies to what is currently called evens.

My edition of the book has a "1 2019" at the bottom of the ISBN page prior to the dedication page. It's possible you have fixed this already, assuming I'm correct.

Best Regards. Interesting book.

bslatkin commented 4 years ago

Thanks for the report. This is one of those classic zero-based indexing vs. ordinal numbers problems. The sentence in there that tries to explain this says:

This lets you take every nth item when slicing a sequence. For example, the stride makes it easy to group by even and odd indexes in a list:

Even means 2nd, 4th, 6th, and odd means 1st, 3rd, 5th. Corresponding indexes are 1, 3, 5 and 0, 2, 4. Perhaps it would be more clear if I changed it from "indexes in a list" to "items in a list"?

bslatkin commented 1 month ago

I ended up going with:

x = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']
odds = x[::2]    # First, third, fifth
evens = x[1::2]  # Second, fourth, sixth
print(odds)
print(evens)

And I used "ordinal position" instead of "indexes".