1

Please help me understand the following code snippet :-

def any(l):
"whether any number is known from list l"
    s = set(list(l)[0])
    for x in l:
        s.intersection_update(set(x))
    return len(s) > 0

Here l is a list containing the list of 3-tuples e.g [(17,14,13),(19,17,2),(22,11,7),(22,13,1),(23,10,5),(23,11,2),(25,5,2)] etc. In particular I am facing difficulty understanding the line 3

s=set(list(l)[0])
1
  • It seems like this function is used to check how many common members of all the tuples in list l. Commented Jun 26, 2012 at 17:58

3 Answers 3

2
set(list(l)[0])

list(l) creates a new list from land then [0] is to fetch its first item, which is (17,14,13). and then set((17,14,13)) returns a set of this tuple. set is a data structure which contains only unique hash-able elements. i.e set((10,12,10)) equals {10,12}

>>> l=[(17,14,13),(19,17,2),(22,11,7),(22,13,1),(23,10,5),(23,11,2),(25,5,2)]
>>> list(l)[0]
(17, 14, 13)
>>> set(list(l)[0])
{17, 13, 14}
Sign up to request clarification or add additional context in comments.

Comments

2

In s=set(list(l)[0]), you're creating a set from the first element of the list. In your case, you could have used set(l[0]) and it would do the same thing. Essentially, you're creating a set based on the first tuple of the list. Overall, your function is trying to find if there is any common element(number) between all tuples.

Comments

0

A set is a python collection of hashable-types that has the special feature that no entity in the collection can repeat (the hash returned from it's __hash__ magic method, and thereby also the boolean return from the __eq__ method cannot be equal to any other entity in the list) It is used wherever a collection is required that can not have repeated entities.

It's hard to tell the intention of the snippet entirely without knowing the context of its use, especially since the values you have for l are all tuples within a container list. The intersection_update is a method of a set that returns a set from the original keeping only elements also found in the one that is passed as an argument. The zero-indexed key is fetching the first tuple from the list.

http://docs.python.org/library/sets.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.