There is: negative indices:
lst[-2]
Answer from Scott Hunter on Stack OverflowLooping until the second to last element in a list, what's best practice?
python - How do I get the last element of a list? - Stack Overflow
python accessing the second to the last element in a list - Stack Overflow
Finding last index of some value in a list in Python
edit: forgot to mention I want the indeces not just the items
the methods I can think of are:
for i in range(len(arr) - 1)
for i, e in enumerate(arr[:len(arr) - 1])
I know range(len(arr)) is frowned upon, but I don't see how it's worse than enumerate in this case. In fact using enumerate on a shortened list and calling len to find the second to last element of that list seems extremely clunky and far less readable.
What's the best practice for doing this?
some_list[-1] is the shortest and most Pythonic.
In fact, you can do much more with this syntax. The some_list[-n] syntax gets the nth-to-last element. So some_list[-1] gets the last element, some_list[-2] gets the second to last, etc, all the way down to some_list[-len(some_list)], which gives you the first element.
You can also set list elements in this way. For instance:
>>> some_list = [1, 2, 3]
>>> some_list[-1] = 5 # Set the last element
>>> some_list[-2] = 3 # Set the second to last element
>>> some_list
[1, 3, 5]
Note that getting a list item by index will raise an IndexError if the expected item doesn't exist. This means that some_list[-1] will raise an exception if some_list is empty, because an empty list can't have a last element.
If your str() or list() objects might end up being empty as so: astr = '' or alist = [], then you might want to use alist[-1:] instead of alist[-1] for object "sameness".
The significance of this is:
alist = []
alist[-1] # will generate an IndexError exception whereas
alist[-1:] # will return an empty list
astr = ''
astr[-1] # will generate an IndexError exception whereas
astr[-1:] # will return an empty str
Where the distinction being made is that returning an empty list object or empty str object is more "last element"-like then an exception object.
The Python slice syntax is alist[start:end:step]. So, with your slice ::-1, you are just reversing the list.
If you want the second element to the last, the correct slice would be
alist[1:]
a = {}
for line in file_a.readlines():
split_line = line.strip().split('\t')
a[split_line[0]] = split_line[1:]
a = {}
for line in file_a:
split_line = line.strip().split('\t')
a[split_line[0]] = split_line[1:]
You slicing expression split_line[::-1] evaluates to split_line reversed, because the third parameter is the step (-1 in this case). You want to start at element 1 and go all the way to the end, with the default step of 1. Check this answer for more on slice notation.