Are all items in list the same?
Dan Sommers
2QdxY4RzWzUUiLuE at potatochowder.com
Tue Jan 8 16:28:32 EST 2019
On 1/8/19 2:31 PM, Tobiah wrote:> On 1/8/19 9:20 AM, Alister wrote:
>> On Tue, 08 Jan 2019 17:15:17 +0000, Alister wrote:
>>
>>> On Tue, 08 Jan 2019 16:48:58 +0200, Serhiy Storchaka wrote:
>>>
>>>> 08.01.19 11:07, Peter Otten пише:
>>>>> Bob van der Poel wrote:
>>>>>
>>>>>> I need to see if all the items in my list are the same. I was using
>>>>>> set()
>>>>>> for this, but that doesn't work if items are themselves lists. So,
>>>>>> assuming that a is a list of some things, the best I've been able to
>>>>>> come up with it:
>>>>>>
>>>>>> if a.count( targ ) == len(a):
>>>>>>
>>>>>> I'm somewhat afraid that this won't scale all that well. Am I
missing
>>>>>> something?
>>>>>
>>>>> a[1:] == a[:-1]
>>>>>
>>>>> :)
>>>>>
>>>>>
>>>> Very clever! It is definitely the shortest solution.
>>>
>>> would that still not return true if the list was a palindrome?
>> ignore me, just tried & ok
>>
>
> You were right the first time. The above comparison should have been
>
> a == a[::-1]
>
> A palindrome will pass.
Let's find out (vertical space added for clarity):
Python 3.7.2 (default, Dec 29 2018, 21:15:15)
[GCC 8.2.1 20181127] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [1, 1, 1, 1, 1]
>>> a[1:] == a[:-1]
True
>>> a == a[::-1]
True
>>> a = [1, 2, 3, 4, 3, 2, 1]
>>> a[1:] == a[:-1]
False
>>> a == a[::-1]
True
Looks like Peter's pretty clever after all. :-)
Dan
More information about the Python-list
mailing list