Jbthomp
Jbthomp

Reputation: 11

Compare multiple items in a list at once?

I need to select multiple items from a list and see if they are all the same or not. Something like this:

    if list1[:3] == 'x':
        Do Something....

So I need to know if items 0-3 in the list equal the character 'x'. I'm just not sure how to do this.

Upvotes: 0

Views: 484

Answers (4)

simon.sim
simon.sim

Reputation: 149

You can also do:

if {x} == set(list1[:3]):
    #do something

Upvotes: 0

aluriak
aluriak

Reputation: 5847

The most readable/efficient way seems to be:

 if all(v == 'x' for v in list[:3]):
    # do something

Upvotes: 1

Oleg Imanilov
Oleg Imanilov

Reputation: 2751

Use something like this:

subArr = list1[:3]
if len([i for i in subArr if i == 'x']) == len(subArr):
  #OK

Upvotes: 0

user6553691
user6553691

Reputation: 41

One way to do it at once may be:

if list[:3] == 3*['x']:
    # DO something

Hope this helps.

Upvotes: 4

Related Questions