Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What's the best way of comparing slices of a list in Python?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading