0

How can I access the strings of 'X'

list = [['X','Y','Z'], ['X','Z','Y']]

For example I want to define a function to return True if list[1] of both list is equal to 'X'

Padraic Cunningham
181k30 gold badges264 silver badges327 bronze badges
asked Aug 26, 2015 at 9:39
4
  • 1
    all('X' in x[0] for x in your_list) Commented Aug 26, 2015 at 9:41
  • that's an answer, write it and sign the question as answered:) Commented Aug 26, 2015 at 9:43
  • I could; but it is too trivial; OP did not try a bit. Commented Aug 26, 2015 at 9:44
  • all('X' in x[0] for x in your_list) is wrong, "X" in "FOO X" is True Commented Aug 26, 2015 at 9:46

2 Answers 2

1

You can use all to see if all ith elements in each sublist are the same:

def is_equal(l, i):
 first = l[0][i]
 return all(sub[i] == first for sub in l)

You might want to catch an IndexError in case i is outside the bounds of and sublist:

def is_equal(l, i):
 try:
 first = l[0][i]
 return all(sub[i] == first for sub in l)
 except IndexError:
 return False

If you want to explicitly pass a value to check:

def is_equal(l, i, x):
 try:
 return all(sub[i] == x for sub in l)
 except IndexError:
 return False
answered Aug 26, 2015 at 9:42
1
  • @Eric, no worries, you may want to let a user know if i was outside the bounds of any sublist Commented Aug 26, 2015 at 9:49
1
def check_list(list):
 for a in list:
 if a == "X"
 return True
 return False
def check_list_list(list):
 try:
 return check_list(list[1])
 except IndexError:
 return False
answered Aug 26, 2015 at 9:48
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.