Reputation: 11
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
Reputation: 5847
The most readable/efficient way seems to be:
if all(v == 'x' for v in list[:3]):
# do something
Upvotes: 1
Reputation: 2751
Use something like this:
subArr = list1[:3]
if len([i for i in subArr if i == 'x']) == len(subArr):
#OK
Upvotes: 0
Reputation: 41
One way to do it at once may be:
if list[:3] == 3*['x']:
# DO something
Hope this helps.
Upvotes: 4