Introduction to the list subtraction operation implemented in Python

Source: Internet
Author: User
problem Description: Suppose I have such a list of two,

One is list1,list1 = [1, 2, 3, 4, 5]
One is list2,list2 = [1, 4, 5]
How do we get a new list,list3,
The LIST3 includes all elements in the list1 that are not present in the List2.
That is: List3 = List1–list2

Solution: We can operate with set (set)
LIST3 = List (set (List1) –set (LIST2))

The set operation converts a list into a collection.
Hypothesis: list_t = [1, 2, 3, 1]
Then: List (Set (list_t)) = [1, 2, 3]
Yes, duplicate entries are deleted.

Other scenarios:list3 = [I for i in List1 if I is not in List2] #可用于list分片
This is also very intuitive to write.
But when the list is large, no set method is fast.

Additional knowledge:a = [[I,j] for I in range (2) for J in Range (3)]
This is very similar to "other schemes",
are judged and calculated in [].
Feel very convenient, at least more convenient and faster than the following:
A = []
For I in range (2):
For j in Range (3):
A.append ([i,j])

Some questions: if list_tmp = [[1,2],[2,3]]
That is, the list is not composed of individual elements, but lists,
Then set (LIST_TMP) will have a problem.

also to study:hash function

  • 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: info-contact@alibabacloud.com 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.