1

I would like to make the for... if in the following code into one line:

cities = ["Berlin", "Berlin", "Berlin", "London"]

unique_cities = []

for city in cities:
    if city not in unique_cities:
        unique_cities.append(c)

print unique_cities

I imagine something like this:

unique_cities = [city for city in cities if city not in unique_cities]

which of course doesn't work because unique_cities is not defined in that loop.

How would I make a one-liner out of this?

Juicy
  • 11,840
  • 35
  • 123
  • 212

2 Answers2

1

If order is not important, the easier way to accomplish this is just

unique_cities = list(set(cities))
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

I think it would be easier to turn it into a set:

unique_cities = set(cities)
John Szakmeister
  • 44,691
  • 9
  • 89
  • 79