3 Replies - 1422 Views - Last Post: 03 April 2011 - 01:58 PM Rate Topic: -----

#1 passer_by   User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 234
  • Joined: 06-March 11

Good way to remove repetitions of Int in a List ?

Posted 03 April 2011 - 11:58 AM

Hi guys,
I've almost finished my lovely task ,however ,the last thing I need to do is to remove repetitions from a list .
I can do it in the old fashion way with two While loops , and run for every item and check for index of item + 1 until the end ...but I'm looking for something else..

any ideas ?
Regards,Ron
Is This A Good Question/Topic? 0
  • +

Replies To: Good way to remove repetitions of Int in a List ?

#2 BetaWar   User is offline

  • #include "soul.h"
  • member icon

Reputation: 1528
  • View blog
  • Posts: 8,314
  • Joined: 07-September 06

Re: Good way to remove repetitions of Int in a List ?

Posted 03 April 2011 - 12:00 PM

You could make a set from the list and then put it back in a list again. Sets only allow for one copy of each entry so all duplicates will be removed without you having to do any extra work.

Hopefully that makes sense.
Was This Post Helpful? 1
  • +
  • -

#3 Simown   User is offline

  • Blue Sprat
  • member icon

Reputation: 322
  • View blog
  • Posts: 650
  • Joined: 20-May 10

Re: Good way to remove repetitions of Int in a List ?

Posted 03 April 2011 - 12:08 PM

Hi Ron,

How I like to do it is use a set, as you may or may not know from theory, a set is the same set if repeats are eliminated. Therefore a list cast to a set will remove repeats! This is assuming you want all repeats to be removed (integer or not).

>>> a = [1, 2, 2, 3, 4, 1, 2, 3, 5, 4, 2, 1, 1]
>>> b = set(a)

>>> print "a is", a
>>> print "b is", b
...

a is [1, 2, 2, 3, 4, 1, 2, 3, 5, 4, 2, 1, 1]
b is set([1, 2, 3, 4, 5])



You could work directly with a set or cast it back to list if you required:

>>> a = [1, 2, 2, 3, 4, 1, 2, 3, 5, 4, 2, 1, 1]
>>> b = set(a)

>>> print "a is", a
>>> print "b is", list(B)/>
...

a is [1, 2, 2, 3, 4, 1, 2, 3, 5, 4, 2, 1, 1]
b is [1, 2, 3, 4, 5]



Even more concisely:

>>> a = [1, 2, 2, 3, 4, 1, 2, 3, 5, 4, 2, 1, 1]
>>> print "a is", a
>>> a = list(set(a))
>>> print "a is now", a
...

a is [1, 2, 2, 3, 4, 1, 2, 3, 5, 4, 2, 1, 1]
a is now [1, 2, 3, 4, 5]



Hope that helps :)


Edit: Too slow again! This is what BetaWar said but more verbose.

This post has been edited by Simown: 03 April 2011 - 12:11 PM

Was This Post Helpful? 1
  • +
  • -

#4 passer_by   User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 234
  • Joined: 06-March 11

Re: Good way to remove repetitions of Int in a List ?

Posted 03 April 2011 - 01:58 PM

So simple !!! can't believe it .

Thanks to both of you .

And yeah,I'm a newbie in Python :)

Ron
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1