4 ms·
This is confusing for beginners and should be avoided. That doesn't follow. Beginners need to learn list slicing to get anywhere with Python, and by the time
by jodrellblank 18y ago
This is confusing for beginners and should be avoided.
That doesn't follow.
Beginners need to learn list slicing to get anywhere with Python, and by the time they've got through [1], [0:10], [2:], [:5], [:-1], [0:10:2] and so on then [:] is just another use in the same pattern.
- quantumhobbit 18y agoI have to admit that slices were the hardest part of learning python for me. Mostly because it took me awhile to find as clear an explanation of their "pass by value" behavior, to borrow C terminology. Slicing incredibly powerful, though and should be given greater attention in intro materials.
- palish 18y agoDrat, the only one I don't know is [0:10:2]. I guess it's back to The Python Tutorial for me. http://docs.python.org/tutorial/ http://docs.python.org/tutorial/ Followup: The tutorial didn't seem to mention what [x:y:z] does, so I checked: >>> range(15) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] >>> range(15)[0:10] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(15)[0:10:2] [0, 2, 4, 6, 8] >>> range(15)[0:10:3] [0, 3, 6, 9] So the third argument is the number of elements to skip (minus one) between each item in the new sequence. Neat.
- nadim 18y agoI also found this: http://www.python.org/doc/2.3.5/whatsnew/section-slices.html http://www.python.org/doc/2.3.5/whatsnew/section-slices.html These are "extended slices" and the third argument is the step. This link also explores deletion and the __getitem__ method: One can also now pass slice objects to the __getitem__ methods of the built-in sequences: >>> range(10).__getitem__(slice(0, 5, 2)) [0, 2, 4] Or use slice objects directly in subscripts: >>> range(10)[slice(0, 5, 2)] [0, 2, 4]
- limmeau 18y agoAnd while we're at confusion and beginners: at least them = things[:] looks different from them = (list) things; which in C-like languages usually does not make a copy of things. Using slices may avoid fallacies like "I know that int(x) is something like a cast of x to int, so list(x) is like a cast of x to list, which does nothing when x is a list".