Thursday 26 April 2012

How do you remove duplicates from a list? | Python

If you don't mind reordering the list, sort it and then scan from the end of the list, deleting duplicates as
you go:
if List:
List.sort()
last = List[-1]
for i in range(len(List)-2, -1, -1): if last==List[i]: del List[i]
else: last=List[i]
If all elements of the list may be used as dictionary keys (i.e. they are all hash able) this is often faster
d = {}
for x in List: d[x]=x
List = d.values()
How do you make an array in Python?
Use a list:
["this", 1, "is", "an", "array"]
Lists are equivalent to C or Pascal arrays in their time complexity; the primary difference is that a Python list can contain objects of many different types.
The array module also provides methods for creating arrays of fixed types with compact representations, but they are slower to index than lists. Also note that the Numeric extensions and others define array-like structures with various characteristics as well.
To get Lisp-style linked lists, you can emulate cons cells using tuples: lisp_list = ("like", ("this", ("example", None) ) )
If mutability is desired, you could use lists instead of tuples. Here the analogue of lisp car is lisp_list[0] and the analogue of cdr is lisp_list[1]. Only do this if you're sure you really need to, because it's usually a lot slower than using Python lists.