Home > front end >  What's the best way of comparing slices of a list in Python?
What's the best way of comparing slices of a list in Python?

Time:11-12

I attempted to compare slices of a list in Python but to no avail? Is there a better way to do this?

My Code (Attempt to make slice return True)

a = [1,2,3]

# Slice Assignment
a[0:1] = [0,0]

print(a)


# Slice Comparisons???
print(a[0:2])
print(a[0:2] == True)
print(a[0:2] == [True, True])

My Results

[0, 0, 2, 3]
[0, 0]
False
False

CodePudding user response:

Since slicing returns lists and lists automatically compare element-wise, all you need to do is use ==:

>>> a = [1, 2, 3, 1, 2, 3]
>>> a[:3] == a[3:]
True

To compare to a fixed value, you need a little more effort:

>>> b = [1, 1, 1, 3]
>>> all(e == 1 for e in b[:3])
True
>>> all(e == 1 for e in b[2:])
False

Bonus: if you are doing lots of array calculations, you might benefit from using numpy arrays:

>>> import numpy as np
>>> c = np.array(b)
>>> c[:3] == 1  # this automatically gets applied to all elements
array([ True,  True,  True])
>>> (c[:3] == 1).all()
True

CodePudding user response:

It is not quite clear what you're trying to do exactly,

As you printed, a[0:2] is [0,0], you're trying to compare the list to a boolean which are different types so they are different

In the second one, you are comparing [0,0] to [True, True], python compares the lists element by element, and 0 evaluvates to false, so [False, False] is clearly not == to [True, True]

Could you edit your question and add what you want the code to do? I would add this in a comment but I dont have enough rep yet :)

  • Related