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:
Now we can create a set without using the set() function: (The feature is available in Python 3.x and Python 2.7)
And here is an example of set comprehension (similar to list 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
http://ozkatz.github.com/improving-your-python-productivity.html
Thanks anyways