Skip to content
Home » Sets in Python – the Basics

Sets in Python – the Basics

Spread the love

Today we’ll be talking about sets.

Here’s the video version of this article:

A set is an unordered collection of unique and immutable objects.

The Features of Sets

Here are the most important features of sets:

– Sets are mutable but they can’t contain mutable objects.

– We can define sets either using curly braces or using the built-in set function.

Defining Sets

Here’s how we define sets in curly braces:

 >>> flowers = {"carnation", "daffodil", "rose", "pansy"}
 >>> flowers
 {'pansy', 'rose', 'carnation', 'daffodil'} 

We can create sets out of sequences (strings, lists, tuples). This time let’s use the set(sequence) function. Any repeating elements in the sequence will not get into the set.

Here’s an example with a string:

 >>> text = "hello"
 >>> set(text)
 {'l', 'o', 'h', 'e'} 

Here’s an example with a list:

 >>> colors = ["blue", "red", "yellow", "red", "orange", "black", "red", "blue"]
 >>> set_of_colors = set(colors)
 >>> set_of_colors
 {'black', 'red', 'orange', 'yellow', 'blue'} 

Finally an example with a tuple. This time we’re passing the literal directly as the argument of the method set:

 >>> set((1, 4, 3, 5, 4, 2, 1 ,3 ,5, 2, 4, 1, 3))
 {1, 2, 3, 4, 5} 

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

The elements of a set must be immutable. If we try to make a set of mutable elements, like lists, we get an error:

 >>> set(([2, 3], [4, 7, 8], [2, 3]))
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
 TypeError: unhashable type: 'list' 

If we need to create an empty set, we must use the set function:

 >>> speaking_plants = set()
 >>> type(speaking_plants)
 <class 'set'> 

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love
Tags:

Leave a Reply