Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including first and last elements in list comprehension

Tags:

python

I would like to keep the first and last elements of a list, and exclude others that meet defined criteria without using a loop. The first and last elements may or may not have the criteria of elements being removed.

As a very basic example,

aList = ['a','b','a','b','a']

[x for x in aList if x !='a']

returns ['b', 'b']

I need ['a','b','b','a']

I can split off the first and last values and then re-concatenate them together, but this doesn't seem very Pythonic.

like image 354
Tony Laidig Avatar asked Dec 03 '25 12:12

Tony Laidig


1 Answers

You can use slice assignment:

>>> aList = ['a','b','a','b','a']
>>> aList[1:-1]=[x for x in aList[1:-1] if x !='a'] 
>>> aList
['a', 'b', 'b', 'a']
like image 98
dawg Avatar answered Dec 05 '25 03:12

dawg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!