-1

I have learned that I can use the so-called list comprehension to make python 'for loops' shorter if I want to create a list. For example, instead of writing:

b = []
a = [2, 3, 5]
for x in a:
    b.append(x**2)

I can write my code like this:

b = [x**2 for x in a]

I was wondering how can I convert the below code to the second shorter format:

lst = [1, 2, 3, 3, 4, 5, 5]
u_lst = []
for x in lst:
    if x not in u_lst:
        u_lst.append(x)
Amin Ba
  • 1,603
  • 1
  • 13
  • 38
  • not all loops can be converted to list comprehensions in ways that make sense. list comprehensions are best suited when you need to "map/do something on every value" in a list, or "filter/select specific items based on independent conditions" in a list, or some combination thereof. list comprehensions are best suited when you want to create a list as an output. Here, your list under construction itself is involved in the conditional. That doesn't resolve to a clean comprehension and a normal loop may simply make more sense here. – Paritosh Singh Feb 15 '19 at 18:50

2 Answers2

0

As @PritoshSingh has pointed out in the comment, a list construction that involves references to items already constructed in the same list is not suitable for the use of a list comprehension, which is best for value mapping and/or filtering based on conditions not involving the list being constructed itself.

The problem you're describing can be best solved by using the dict.from_keys method, which ignores items it has already seen as it reads from the given sequence:

u_list = list(dict.from_keys(lst))

Use collections.OrderedDict in place of dict if you're using Python 3.6 or earlier versions, where order of dict keys is not guaranteed.

blhsing
  • 91,368
  • 6
  • 71
  • 106
0

From the specific example given it seems like you want u_lst to be a list of unique values only. If so, there is no need for any list comprehensions, just use a set on the original list:

lst = [1, 2, 3, 3, 4, 5, 5]
u_lst = list(set(lst))

Outputs {1, 2, 3, 4, 5} without converting into a list and [1, 2, 3, 4, 5] with it.

Note that using set on a list produces a set, to get it to behave as a list, you would then convert it into a list as above.