0

['2C', '2S', '2H'] If i have a list like above, how do I check if each element in the list starts with 2. But the two can change to any number or at times it could be replaced with a A to fill in the gap. e.g : ['2C', '2S', 'AH']

  • Does this answer your question? [Checking whether a string starts with XXXX](https://stackoverflow.com/questions/8802860/checking-whether-a-string-starts-with-xxxx) – sushanth May 15 '21 at 13:31
  • it's a string, so you can loop over the list and check with `startswith('2')` – Sammy J May 15 '21 at 13:31
  • Your question is not clear. what gap, is there any pattern to the 2 changing to fill? – Ade_1 May 15 '21 at 13:31

2 Answers2

1

I'm assuming you want to output true if every element starts with a 2 and false otherwise

Thanks to @chepner for suggesting to use a generator

listA = ['2C', '2S', '2H']
listB = ['2C', '2S', 'AH']

all(i[0] == '2' for i in listA)     # true
all(i[0] == '2' for i in listB)     # false
Orbital
  • 565
  • 3
  • 13
  • 1
    If you use a generator expression instead of a list comprehension, `all` can stop as soon as it finds a non-matching element. `all(i[0] == '2' for i in listA)`. (That is, you don't have compare every element to `'2'` before `all` starts checking the results.) – chepner May 15 '21 at 13:38
  • Thanks. I will edit my post accordingly – Orbital May 15 '21 at 13:39
  • And to not hard-code the '2', do `i[0] == listA[0][0]` or assign that to a variable first so that it's not re-evaluated for every iteration: `first = listA[0][0]; all(i[0] == first for i in listA)` (but needs a check first to ensure the list is non-empty). Since the OP said _"But the two can change to any number"_. – aneroid May 15 '21 at 14:11
0
x = ['2C', '2S', 'AH']
y = ['2C', '2S', '2H']
for i, j in zip(x, y):
    if i[0] != j[0]: 
        print('Item {} in list x and item {} in list y are not starting with same character'.format(i, j)

You would get the following result

Item AH in list x and item 2H in list y are not starting with same character