Python performance: Do not use the key in list to determine if key is in the list

Source: Internet
Author: User

Original: Https://docs.quantifiedcode.com/python-anti-patterns/performance/using_key_in_list_to_check_if_key_is_ Contained_in_a_list.html

Using the key in list to iterate the list will potentially cost n iterations to complete, and N is the key in the list position. If allowed, the list can be converted to set or dict, because Python finds elements in set or dict by directly accessing them without needing an iteration, which is much more efficient.

Anti-pattern

The following code defines a list type L, and then calls if 3 in L to check if 3 is in L. This is inefficient. This is followed by the fact that Python iterates through the list until it finds 3 or iterates through the list.

L = [1, 2, 3, 4]#  iterates over three elements in the listif in L:    Print("Thenumber 3 is in thelist. " Else:    print("Thenumber 3 is not in thelist. ")
Recommended practice using Set or dict instead of list

The modified code is as follows and the list turns into set. More efficient behind this is because in Python, set attempts to directly access the target value rather than comparing each element in the iteration list with the target value.

s = Set ([1, 2, 3, 4])if in s:    print("Thenumber 3 was in thel ist. " Else:    print("Thenumber 3 is not in thelist. ")

Python performance: Do not use the key in list to determine if key is in the list

Related Article

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.