0
#for 1d lists
x = [1,2,3]
y = [1,2,3]
print([True if x[i]==y[i] else False for i in range(len(x))])

#for 2d lists
d=[[0,0,0,0],[0,0,0,0],[0,0,0,0]]
e=[[0,0,1,0],[0,0,0,0],[0,0,0,0]]

for i in range(0,len(d)):
    for j in range(0,len(d[i])):
          if d[i][j]==e[i][j]:
               continue
          else 
              print (false)
print(true) 

for 2d lists i am using two for loops(nested) and comparing each element with other(d[i][j]==e[i][j])...is there any better method? Assume both lists are of same size i am new to python with little C background Is it possible without numpy library?

3
  • d==e seems to work....can i use it?? Commented Mar 17, 2018 at 16:28
  • how does == be compared? will it check each element internally? Commented Mar 17, 2018 at 16:30
  • [True if x[i]==y[i] else False for i in range(len(x))] => [x[i]==y[i] for i in range(len(x))] don't use ternary to return true or false. Commented Mar 17, 2018 at 16:36

1 Answer 1

2

See Chapter 5 in the Python documentation – Comparing Sequences and Other Types:

The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively. If all items of two sequences compare equal, the sequences are considered equal.

You should use the == operator, which is overloaded to work for collections (and pretty much any two comparable objects) too.

Sign up to request clarification or add additional context in comments.

Comments