lyst[:None]

Anton Muhin antonmuhin at sendmail.ru
Fri May 23 11:50:30 EDT 2003


Anton Muhin wrote:
>>
>> Is there a way of doing this on one line?
>>
>> (Yes, I know I can split it up onto several lines, and probably should
>> if I want humans to understand the code ...)
> 
> 
> I might be missing something, but still I would prefer:
> 
> def get_elements(l, count = None):
>     if count:
>         return l[:count]
>     else:
>         return l[:]
> 

Oops, I skipped one-line condition. Several more solution:

1. l[:n] + [l[n]]
But it changes semantics a bit:
 >>> l = range(10)
 >>> l[:0] + [l[0]]
[0]
 >>> l[:1] + [l[1]]
[0, 1]
 >>> l[:10] + [l[10]]
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
IndexError: list index out of range
 >>> l[:9] + [l[9]]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>>

2. (l[:n], l[:])[n == -1]
-1 gets the whole list

3. (l[:n], l[:])[n == None]
None gets the whole list

hth,
anton





More information about the Python-list mailing list