Asim Khan
Asim Khan

Reputation: 11

How to write following code using list comprehensions?

I started learning list comprehensions recently. Here I'm trying to convert this code into list comprehension but unable to come up with.

def pairs_smaller1(lst):
  result =[]
  for element in range(len(lst)):
    temp = []
    value = lst[element]
    for value_for_comparison in range(len(lst)):
      if int(lst[value_for_comparison]) < value:
        temp.append(lst[value_for_comparison])
    result.append((value,temp))
  return result 

Upvotes: -1

Views: 72

Answers (2)

Blckknght
Blckknght

Reputation: 104702

You could improve your code quite a bit by iterating directly on the values in your list, rather than using range to iterate over indexes:

def pairs_smaller1(lst):
  result =[]
  for x in lst:
    temp = []
    for y in lst:
      if int(y) < x:
        temp.append(y)
    result.append((x,temp))
  return result 

Because that's so much more compact (not hurt by my choice of shorter variable names), you can pretty easily turn that into a couple of nested list comprehensions without compromising readability by much:

result = [(x, [y for y in lst if int(y) < x]) for x in lst]

Upvotes: 1

user7804910
user7804910

Reputation:

You can process in a bottom-up fashion:

def pairs_smaller1(lst):
  result =[]
  for element in range(len(lst)):
    temp = []
    value = lst[element]
    temp = [ lst[vfc] for vfc in range(len(lst)) if int(lst[vfc]) < value ]
    result.append((value,temp))
  return result 

Then:

def pairs_smaller1(lst):
  return [(lst[e],[ lst[vfc] for vfc in range(len(lst)) if int(lst[vfc]) < lst[e]]) for e in range(len(lst))]

But this is very difficult to read and isn't more efficient, so it must be avoided.

Upvotes: 3

Related Questions