How to Remove repeated elements in the list using Python

Source: Internet
Author: User
Tags python list
This article mainly introduces how to remove repeated elements from the list in Python. The example shows how to remove repeated elements from the list in Python, for more information about how to remove repeated elements in the Python list, see the example in this article. Share it with you for your reference. The details are as follows:

The built-in set is easier to remember.

l1 = ['b','c','d','b','c','a','a']l2 = list(set(l1))print l2

There is also a speed difference that is said to be faster and never tested.

l1 = ['b','c','d','b','c','a','a']l2 = {}.fromkeys(l1).keys()print l2

Both of them have a disadvantage. sorting changes after removing duplicate elements:

['a', 'c', 'b', 'd']

If you want to keep their original order:

Use the sort method of the list class

l1 = ['b','c','d','b','c','a','a']l2 = list(set(l1))l2.sort(key=l1.index)print l2

You can also write it like this.

l1 = ['b','c','d','b','c','a','a']l2 = sorted(set(l1),key=l1.index)print l2

You can also use traversal

l1 = ['b','c','d','b','c','a','a']l2 = []for i in l1:  if not i in l2:    l2.append(i)print l2

The above code can also be written like this

l1 = ['b','c','d','b','c','a','a']l2 = [][l2.append(i) for i in l1 if not i in l2]print l2

In this way, the sorting will not change:

['b', 'c', 'd', 'a']

I hope this article will help you with Python programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.