alc
alc

Reputation: 309

Slice lists at different indices at the same time in python

How can I check if two lists have same values at specific index, using slice?

L1 = ['X00013', 9654123, 4.1, 'No', 'No', 1.83, 3.8, 0.01, 90.01]
L2 = ['X00014', 2021230, 1.23, 'Yes', 'No', 1.86, 3.65, 0.15, 0.00001]

I know how to check

if L1[3] == L2[3]:
    print("YES")

but I do not know how to check for multiple locations/indices at the same time:

I'm looking for something like checking both lists at indices 3,4 and 7 at the same time.

I can use operator and itemgetter:

itemgetter(3,4,7)(L1) ==  itemgetter(3,4,7)(L2)

but I would like the simple direct solution slicing the lists. Thank you for your help.

Upvotes: 1

Views: 120

Answers (2)

RoadRunner
RoadRunner

Reputation: 26315

You can do this with just a basic loop and some conditions:

def check_places(L1, L2, places):
    for i in places:
        if i >= len(L1) or i >= len(L2) or L1[i] != L2[i]:
            return False

    return True

Which works as follows:

>>> L1 = ['X00013', 9654123, 4.1, 'No', 'No', 1.83, 3.8, 0.01, 90.01]
>>> L2 = ['X00014', 2021230, 1.23, 'Yes', 'No', 1.86, 3.65, 0.15, 0.00001]
>>> places = (3, 4, 7)
>>> check_places(L1, L2, places)
False

Upvotes: 0

Prune
Prune

Reputation: 77837

You can iterate through a list of desired indices.

places = (3, 4, 7)

if [L1[i] for i in places] ==     \
   [L2[i] for i in places]:
    print "YES"
else:
    print "NO"

Of course, this reduces to a simple if all, but the above might help you understand the logic.

print all(L1[i] == L2[i] for i in places)

Upvotes: 1

Related Questions