Reprint: Python list and set performance comparison + both conversion

Source: Internet
Author: User

Performance comparison (transfer from http://www.linuxidc.com/Linux/2012-07/66404.htm)

I knew it was more efficient to use set in Python, but I didn't think there was such a big gap:

~$ python-m Timeit-n "[x for X in range (+) if x in range (500, 1500)]"

Loops, Best of 3:28.2 msec per loop

~$ python-m Timeit-n "set (range). Intersection (range (500, 1500))"

Loops, Best of 3:120 usec per loop

The List is about 225 times times the set time. List-to-set does not have much time, so it is best to use set when there is a need to ask for the set and intersection of (collections, lists, etc.).

Update

Considering that range (500, 1500) was called 1000 times (which would be time-consuming), it was changed to only one call, and the time dropped from 28.2msec to 18.2msec. It's still about 150 times times slower (than set).

~$ python-m timeit-n "Range1500=range (500, 1500); [x for X in range (+) if x in range1500] "

---------------------------------------------------------------------------------------

The set is converted to the list method as follows: The list is converted to the Set method as follows:

s = set (' 12342212 ') L = [' 12342212 ']

Print S # set ([' 1 ', ' 3 ', ' 2 ', ' 4 ']) s = set (L[0])

l = List (s)                                                                              Print s    # set ([' 1 ', ' 3 ', ' 2 ', ' 4 '])

L.sort () # Sort m = [' 11 ', ' 22 ', ' 33 ', ' 44 ', ' 11 ', ' 22 ']

Print L # [' 1 ', ' 2 ', ' 3 ', ' 4 '] print set (m) # set ([' 11 ', ' 33 ', ' 44 ', ' 22 '])

Visible set and lsit can be freely converted, when deleting multiple/massive duplicate elements in the list,

You can convert to set and then back to list and sort (set is not sorted). This method is not only convenient but also highly efficient.

Reprint: Python list and set performance comparison + both conversion

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.