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

List comprehension with loop and conditions

I’d like to transform this Python code (below) into a list comprehension :

def list1(a):
  L = [100]
  n = int((L[0] - a)/0.2)
  for i in range (n):
    var = L[i]-0.2
    var = round(var,2) if var * 100 % 100 != 0 else int(var)
    L.append(var)
  return L

print(list1(25))

I’ve tried that but it didn’t work :

def list2(a):
  L = [100]
  n = int((L[0] - a)/0.2)
  i = 0
  var = L[i]-0.2
  L = [L[i]-0.2 for i in range (n) round(var,2) if (var) * 100 % 100 != 0 else int(var)]
  return L

print(list2(25))

Can you help me please ?

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

>Solution :

You can access a list while building the list using a generator expression with list.extend. This approach has no advantages over a for loop and is less readable. Using a single list comprehension is not possible in your use case.

def list2(a):
  L = [100]
  n = int((L[0] - a)/0.2)
  L.extend(round(L[i]-0.2,2) if (L[i]-0.2) * 100 % 100 != 0 else int(L[i]-0.2) for i in range(n))
  return L
list2(25) == list1(25)

Output

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