Mumfordwiz
Mumfordwiz

Reputation: 1545

trying to write a loop in one line

I'm using python 3.3 i have been trying to write this line in one line and I can't manage.

   plop = []
   for i in range (len(list1)):
      if list1[i] != list1[i-1]:
           plop.append(list1[i])

I don't care overwriting list1 if needed, and not using "plop" at all, I don't want to use set as well. Thanks!

p.s edited was a typo, sorry

Upvotes: 0

Views: 91

Answers (2)

Joachim Isaksson
Joachim Isaksson

Reputation: 180877

I'm not sure why the 'single line' requirement, but you could do it using a comprehension;

plop = [new_ls[i] for i in range(len(list1)) if list1[i] != list1[i-1]]

...or if you're not really meaning to compare the first and the last element for the first value;

plop = [v for (x,y,v) in zip(list1, [None]+list1, new_ls) if x != y]

Upvotes: 2

Jon Clements
Jon Clements

Reputation: 142106

Much more readable (and not so prone to index errors - unless you are meant to be comparing the first element with the last, and the second with the first etc...) way of removing consecutive duplicates is if you just did:

from itertools import groupby
plop = [k for k, g in groupby(list1)]

And of course, you could "one line it" :)

from itertools import groupby; plop = [k for k, g in groupby(list1)]

Or, if not using a set, and there can't be any duplicates - contiguous or not:

from collections import OrderedDict
plop = list(OrderedDict.fromkeys(list1))

Upvotes: 3

Related Questions