Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most pythonic way to truncate a list to N indices when you can't guarantee the list is at least N length?

Tags:

python

What is the most pythonic way to truncate a list to N indices when you can not guarantee the list is even N length? Something like this:

l = range(6)

if len(l) > 4:
    l = l[:4]

I'm fairly new to python and am trying to learn to think pythonicly. The reason I want to even truncate the list is because I'm going to enumerate on it with an expected length and I only care about the first 4 elements.

like image 446
user548448 Avatar asked Feb 19 '12 18:02

user548448


3 Answers

Python automatically handles, the list indices that are out of range gracefully.

In [5]: k = range(2)

In [6]: k[:4]
Out[6]: [0, 1]

In [7]: k = range(6)

In [8]: k[:4]
Out[8]: [0, 1, 2, 3]

BTW, the degenerate slice behavior is explained in The Python tutorial. That is a good place to start because it covers a lot of concepts very quickly.

like image 151
Praveen Gollakota Avatar answered Oct 14 '22 18:10

Praveen Gollakota


You've got it here:

lst = lst[:4]

This works regardless of the number of items in the list, even if it's less than 4.

If you want it to always have 4 elements, padding it with (say) zeroes or None if it's too short, try this:

lst = (lst + [0] * 4)[:4]

When you have a question like this, it's usually feasible to try it and see what happens, or look it up in the documentation.

It's bad idea to name a variable list, by the way; this will prevent you from referring to the built-in list type.

like image 25
kindall Avatar answered Oct 14 '22 16:10

kindall


All of the answers so far don't truncate the list. They follow your example in assigning the name to a new list which contains the first up to 4 elements of the old list. To truncate the existing list, delete elements whose index is 4 or higher. This is done very simply:

del lst[4:]

Moving on to what you really want to do, one possibility is:

for i, value in enumerate(lst):
    if i >= 4:
        break
    do_something_with(lst, i, value)
like image 20
John Machin Avatar answered Oct 14 '22 17:10

John Machin