Trying to adapt further from this question on stackoverflow:
How to convert a set to a list in python?
I have been trying to solve this riddle on interactivepython.org The riddle is exactly on the end of the page and it goes like...
We have a list, for eg list1 = ['cat','dog','rabbit']
and now using list comprehension (strictly list comprehension), we have to create a list of each alphabet in the each word in list1 and the resulting list should not contain duplicates.
So the expected answer is something like:
['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']
Its alright even if the sequence is not maintained.
Now first to create a list of all characters, used:
print [word[i] for word in list1 for i in range(len(word))]
and it gives output
['c', 'a', 't', 'd', 'o', 'g', 'r', 'a', 'b', 'b', 'i', 't']
This includes duplicates as well
so I then created this into set as sets do not contain duplicates:
print set([word[i] for word in list1 for i in range(len(word))])
output:
set(['a', 'c', 'b', 'd', 'g', 'i', 'o', 'r', 't'])
however this returns a set not a list and the same can be verified by:
type(set([word[i] for word in list1 for i in range(len(word))]))
output:
<type 'set'>
Now, in the video on the above given link of interactivepython.org the guy just puts encloses the entire thing after print
in list()
as follows:
print list(set([word[i] for word in list1 for i in range(len(word))]))
and he gets the result output in list, however I don't get the same when I try using idle that uses python 2.7.8. It instead gives me an error:
Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module>
print list(set([word[i] for word in list1 for i in range(len(word))]))
TypeError: 'list' object is not callable
I think this is may be because interactive python uses Python 3 for its tutorials. So is this merely a difference between Python 3 and Python 2.7?
Also, how can I achieve similar output using Python 2.7.8
Thanks