-1

I am faced issue with a list comprehension missing value in a result list. I have two lists. when i am trying with for loop. value is expected as i want to like(7 4 2 -1 0) but i don't need integer values in need list. when use list comprehension i got only 4 value [4, 2, -1, 0]. i don't understand what happens in my logic. if there is anyone you help me kindly see a code.

l1 = [3, 6, 9, 2, 11, 14, 13]
f = [7]

subtraction l1 last element to l1 nth element. I am trying this formula(pls see code more understandable):

l2 = l1[-1]-l1[n]

and after that, i am trying to put if else condition in like this:

if l2 <= f:
        print(l3)

this is the code I am trying in for loop

In [230]: for l2 in l1:
 ...:     l3 = l1[-1]-l2
 ...:     #print(l3)
 ...:     for f1 in f:
 ...:         if l3<=f1:
 ...:             print(l3)
 ...:             
 ...:         
7
4
2
-1
0

And for the List Comprehension code is:

  for f1 in f:
      f1

In [47]: l1 = [x[-1] - l for l in x if l >= int(f1)]
...: 

In [48]: l1
Out[48]: [4, 2, -1, 0]
Najeeb Choudhary
  • 396
  • 1
  • 3
  • 21
  • 2
    Please format code as code. / [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). / Avoid spelling mistakes please. – user202729 Feb 08 '18 at 13:18
  • @user202729 wait – Najeeb Choudhary Feb 08 '18 at 13:19
  • Read this https://stackoverflow.com/questions/8049798/understanding-nested-list-comprehension – Joe Feb 08 '18 at 13:23
  • Are you aware of `l1[-1]` being always the last element of `l1` ? – Joe Feb 08 '18 at 13:27
  • @Joe yep in my case l1[-1] = 13 – Najeeb Choudhary Feb 08 '18 at 13:30
  • The list comprehension you showed does not do the same thing as the `for` loop. First of all what's `x`? The main thing is that you're not checking the same condition (`<=` vs `>=`) and the value being tested is not the same (`l3 <= f1` vs `l >= int(f1)`). Try the following: `[l1[-1] - l for l in l1 if (l1[-1] - l) <= int(f1)]`. **Edit**: A more equivalent translation of your loop: `[l1[-1] - l for l in l1 if any((l1[-1] - l) <= f0 for f0 in f)]` – pault Feb 08 '18 at 13:38
  • @pault ogic is correct I spent whole day on it – Najeeb Choudhary Feb 08 '18 at 13:45

1 Answers1

2

Your list comprehension does not match with your for loop.
You must replace:

[x[-1] - l for l in x if l >= int(f1)]

with:

[(l1[-1] - l) for l in l1 if (l1[-1] - l) <= int(f1)]

which gives the expected output.

(I added parentheses for better readability)

Laurent H.
  • 6,316
  • 1
  • 18
  • 40