howtos » Python: removing repeated values in a list

Python: removing repeated values in a list

CODE:
  1. list = ['one', 'two', 'three', 'one', 'one', 'four', 'two']
  2. #convert the list into a set.  An element can only exist once within a set
  3. set = set(list)
  4. #convert the set back into a list type
  5. list = list(set)
  6. print list

Are those variable names confusing? Let's look at that example again:

CODE:
  1. fruits = ['apple', 'bananas', 'cantaloupes', 'apple', 'apple', 'durian', 'bananas']
  2. #convert the list into a set.  An element can only exist once within a set
  3. fruits_unique = set(fruits)
  4. #convert the set back into a list type
  5. fruits = list(fruits_unique)
  6. print fruits

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <blockquote cite=""> <code> <em> <strong>