Nikhil Prabhu Nikhil Prabhu - 1 year ago 89
Python Question

Python: How is my set being turned into a list?

I've written a program to recursively get all the hyponym-children of a given synset in the wordnet graph.

However, that is not relevant to my question here.

I'm basically adding all the nodes I pass through to a set.
The output I'm getting, however, is a list

Here's my code

import pickle
import nltk
from nltk.corpus import wordnet as wn

feeling = wn.synset('feeling.n.01')
happy = wn.synset('happiness.n.01')

def get_hyponyms(li):
return [x.hyponyms() for x in li]

def flatten(li):
return [item for sublist in li for item in sublist]

def get_hyponyms_list(li):
if li:
return list(set(flatten(get_hyponyms(li))))

def get_the_hyponyms(li, hyps):
if li:
hyps |= set(li)
get_the_hyponyms(get_hyponyms_list(li), hyps)
return hyps

def get_all_hyponyms(li):
hyps = set()
return get_the_hyponyms(li, hyps)

feels = sorted(get_all_hyponyms([feeling]))
print type(feels)

The output is this-

<type 'list'>

Why is this happening?

Answer Source

sorted() creates a list, if you do a simple test, this behavior is clear. The Python documentation says a "set object is an unordered collection of distinct hashable objects".

>>> x = {1,3,2}
>>> sorted(x)
[1, 2, 3]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download