0

I have the following lines of code that are used in a function:

a = [1, 2, 4, 1]
b = [1, 3, 4, 1]
return [a for i in range(len(a)) if a[i] == b[i] and a not in *self*]

It should return [1, 4].

I want to use something similar to the self value in classes.

I can do something like this:

a = [1, 2, 4, 1]
b = [1, 3, 4, 1]
lst = []
for i in len(a):
    if a[i] == b[i] and a[i] not in lst:
        lst.append(a[i])
return lst

or even this

a = [1, 2, 4, 1]
b = [1, 3, 4, 1]
return list(set([a for i in range(len(a)) if a[i] == b[i]]))

(Note that this method may change the order of the items in the list.)

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Paul
  • 162
  • 1
  • 12
  • What was your exact question? It wasn't clear from your title so much. One option would be to convert lists to arrays, subtract both the arrays and wherever the difference will be 0, will be the places (indices) at which the elements are the same. You can then use those indices to get the resulting list. All of this can be done in a single line – Sheldore Dec 12 '18 at 15:34
  • I guess you don't want a beautiful solution but instead want to know if there is a possible way with list comprehension? – user8408080 Dec 12 '18 at 15:35
  • 1
    The solution is as short as `result = list(set(a[a-b==0]))` provided your `a` and `b` are numpy arrays – Sheldore Dec 12 '18 at 15:37
  • @Bazingaa I want to check whether the item that is currently compared exists in the list that is being created with the one line `for` loop. I hope it's clear enough. – Paul Dec 12 '18 at 15:38
  • @Bazingaa Yeah, I think that would be the best solution to the problem, but I am curious if there is some kind of `self` for lists so I can refer to it while looping through. – Paul Dec 12 '18 at 15:42
  • @user8408080 Exactly. The beautiful solution would be the one that Bazingaa showed – Paul Dec 12 '18 at 15:45
  • 2
    note: your last example is building a list to build a set to build a list. the innermost list is redundant, the set constructor accepts an iterator so you can remove the `[]`s from the last line and get the same behaviour – Sam Mason Dec 12 '18 at 16:21

0 Answers0