INTERVIEW QUESTIONS
WEB
PYTHON
DETAILS
Question: How do you remove duplicates from a list?
Answer: 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()
|
Question:
How do you remove duplicates from a list?
Answer:
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() Source: CoolInterview.com
>>> a = [1,2,3,4,4,5,5,6,1,2] >>> list(set(a)) [1, 2, 3, 4, 5, 6] Source: CoolInterview.com
Answered by: Anand Sridharan | Date: 8/21/2010
| Contact Anand Sridharan
If you have the better answer, then send it to us. We will display your answer after the approval.
Rules to Post Answers in CoolInterview.com:-
- There should not be any Spelling Mistakes.
- There should not be any Gramatical Errors.
- Answers must not contain any bad words.
- Answers should not be the repeat of same answer, already approved.
- Answer should be complete in itself.
|