set comprehension in python

As many of you are familiar with list comprehension in Python, let me inform you about set comprehension.

You can create a set from a list or a dictionary. Example:

#create set from list
>>> s = set([1, 2, 3])
>>> s
set([1, 2, 3])

#create set from dictionary (keys)
>>> dt = {1: 10, 2: 20, 3: 30}
>>> dt
{1: 10, 2: 20, 3: 30}
>>> type(dt)
<type 'dict'>
>>> s = set(dt)
>>> s
set([1, 2, 3])

Now we can create a set without using the set() function: (The feature is available in Python 3.x and Python 2.7)
>>> s = {1, 2, 3, 'Bangladesh', 'python', 1.15}
>>> type(s)
<type 'set'>
>>>

And here is an example of set comprehension (similar to list comprehension):
>>> s = { x for x in range(10) }
>>> s
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])


Comments

Nas said…
Oz Katz just blogged about the same thing :)

http://ozkatz.github.com/improving-your-python-productivity.html

Thanks anyways
Tamim Shahriar said…
Interestingly I found the new feature while working on a script today. A coincidence! The link you provided is good post. Thanks.
D L S said…
This comment has been removed by the author.

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code