简体   繁体   中英

Is set() faster than list(), python?

Suppose I have an input which contains space seperated integers which are unique, ie one does not occur twice. In such a case, will using the following,

setA = set(input().split())

be faster than using the below one? If so(I actually experienced it in this way), why?

listA = list(input().split())

Please do not focus on the fact that there is not a conversion to int , while reading the input.

In a problem I am working on, using list() gives timeout, however by using set() , I am able to run it such that it is in the time limitations. I wonder why this is the case?

edit : In case it might be related, the code which is related,

arr = input().split()

for ele in arr:

    if ele in setA:
        happiness += 1
    elif ele in setB:
        happiness += -1
    else:
        pass

Where arr is a space seperated line of integers, no uniquneness this time.

Python's set class represents the mathematical notion of a set, namely a collection of elements, without duplicates, and without an inherent order to those elements. The major advantage of using a set, as opposed to a list, is that it has a highly an optimized method for checking whether a specific element is contained in the set. This is based on a data structure known as a hash table

However, there are two important restrictions due to the algorithmic underpinnings. The first is that the set does not maintain the elements in any particular order. The second is that only instances of immutable types can be added to a Python set. Therefore, objects such as integers, floating-point numbers, and character strings are eligible to be elements of a set. It is possible to maintain a set of tuples, but not a set of lists or a set of sets, as lists and sets are mutable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM