Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Python lists

Tags:

python

list

I have several long lists in python and have compare them and find the lists that are equal to each other except the last elements in the them. Which is the fastest way?

like image 357
Hossein Avatar asked Oct 05 '10 20:10

Hossein


2 Answers

a[:-1] is shorthand for "all the elements of a but the last one." If you need more than 1 element to be excluded, change the 1 to the number you need.

a[:-1] == b[:-1] will compare a and b without their final elements.

See this for more information on slicing.

like image 98
nmichaels Avatar answered Sep 28 '22 05:09

nmichaels


Use something like if list1[:-1] == list2[:-1].

like image 32
Daenyth Avatar answered Sep 28 '22 05:09

Daenyth