Python Forum
Preferred way to slice a list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Preferred way to slice a list (/thread-23068.html)



Preferred way to slice a list - SvetlanaofVodianova - Dec-09-2019

In the Zen of Python, it states:

Quote:There should be one-- and preferably only one --obvious way to do it.

Suppose I have the following list:

a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
I can slice it to print the last 4 digits in two ways:

# Both will print ['e', 'f', 'g', 'h']
print(a[-4:])
print(a[4:])
Which is the Pythonic way of doing it?

I don't like the a[4:] because at first glance it looks like I'm printing the first 4 elements of the list.


RE: Preferred way to slice a list - ichabod801 - Dec-09-2019

Don't worry about the one true way to do things. That is probably the most often broken part of the Zen of Python.

I don't think either [4:] or [-4:] is more Pythonic. Here's how I would think of it. The colon is to the right, so it's printing everything to the right of that index. The first one prints everything after the fourth item, and the second one prints the last four items (because of the negative). If your intent is to get 'the last four digits', then I think [-4:] is clearer. More important than that is what if you get a 9 item list? or a 7 item list. In either of those cases, [-4:] will give you the correct number of items, but [4:] may not give you the right number of items.


RE: Preferred way to slice a list - perfringo - Dec-09-2019

I would add that for better readability one can use slice():

>>> lst = list(“abcde”)
>>> last_four = slice(-4, None)
>>> lst[last_four]
['b', 'c', 'd', 'e']
However, one should keep in mind that no error is raised when list is shorter than four:

>>> lst = list(“abc”)
>>> lst[-4:]
['a', 'b', 'c']
>>> lst[last_four]
['a', 'b', 'c']
>>> lst = list()
>>> lst[-4:]
[]
Code can’t rely on assumption that length of returned list is four.


RE: Preferred way to slice a list - SvetlanaofVodianova - Dec-09-2019

(Dec-09-2019, 10:12 PM)ichabod801 Wrote: In either of those cases, [-4:] will give you the correct number of items, but [4:] may not give you the right number of items.

I ran into that exact problem when I was experimenting on two different lists. I'm embarrassed to say it took me a moment to realize what was going on.