Python

Set Comprehension in Python

In a previous article I discussed list comprehensions. Today I will talk about set comprehensions. Set comprehensions were added to Python in version 2.7 and they are similir to List Comprehensions, the only difference is that we use curly braces instead of square brackets when making them.

A set is an un-ordered collection in which each element can only appear once. Below is an example of a set of the squares of all numbers between 0 and 10:

>>> nums = {x**2 for x in range(10)}
>>> nums
set([0, 1, 4, 81, 64, 9, 16, 49, 25, 36])
>>> 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s