walid
walid

Reputation: 305

How to compare elements in a list without for loop?

I have a list: R = ['123', '1854', '000'] and I want to make sure that all the elements on it have the same length, but I don't want to use a for loop.

I tried this:

if R[::] !== R[::]:
   print('false')

Obviously it does not work.

It's possible to do it without a for loop?

And How to put it as an AssertError like: assert ..., 'False'? if the list elements are length different then raise an AssertError.

Upvotes: 2

Views: 573

Answers (2)

Swetank Poddar
Swetank Poddar

Reputation: 1291

You should probably make a function and call that, but you could do something like this

if len(set(map(len,R))) != 1:
    # Do something, there exists elements of different sizes

Upvotes: 1

lukas.tomoszek
lukas.tomoszek

Reputation: 164

result = any(map(lambda x: len(x) != len(R[0]), R))

Upvotes: 1

Related Questions