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'

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
Sign up to request clarification or add additional context in comments.

1 Comment

@Eric, no worries, you may want to let a user know if i was outside the bounds of any sublist
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

Comments

Your Answer

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