Skip to main content

Command Palette

Search for a command to run...

Day31-Sets

Updated
2 min read
Day31-Sets
C
I am Data Science student, has a little bit knowledge on Web Development. I also love writing and editing as my hobby. Passionate to explore the world.

Python Sets

Sets are unordered collection of data items. They store multiple items in a single variable. Set items are separated by commas and enclosed within curly brackets {}. Sets are unchangeable, meaning you cannot change items of the set once created. Sets do not contain duplicate items.

Example:

info = {"Carla", 19, False, 5.9, 19}
print(info)

Output:

{False, 19, 5.9, 'Carla'}

Here we see that the items of set occur in random order and hence they cannot be accessed using index numbers. Also sets do not allow duplicate values.

Quick Quiz: Try to create an empty set. Check using the type() function whether the type of your variable is a set

Accessing set items:

Using a For loop

You can access items of set using a for loop.

Example:

info = {"Carla", 19, False, 5.9}
for item in info:
    print(item)

Output:

False
Carla
19
5.9

Practice

s = {2, 4, 2, 6}
print(s)

info = {"Carla", 19, False, 5.9, 19}
print(info)

harry = set()
print(type(harry))

for value in info:
  print(value)

Output:

{2, 4, 6}
{False, 19, 5.9, 'Carla'}
<class 'set'>
False
19
5.9
Carla

Explanation

  • s = {2, 4, 2, 6}

    • Creates a set named s.

    • Duplicate values are automatically removed because sets store only unique elements.

  • print(s)

    • Displays the contents of the set.
  • info = {"Carla", 19, False, 5.9, 19}

    • Creates a set containing different data types.

    • Duplicate values are removed automatically.

  • print(info)

    • Displays all elements of the set.
  • harry = set()

    • Creates an empty set.

    • set() is used because {} creates an empty dictionary.

  • print(type(harry))

    • Shows the data type of the variable harry.
  • for value in info:

    • Iterates through each element in the set info.
  • print(value)

    • Prints each element one by one during the loop.

Key Points

  • Sets store only unique values.

  • Duplicate elements are automatically removed.

  • Sets are unordered collections.

  • Sets can contain elements of different data types.

  • Use set() to create an empty set.

100DaysofPython

Part 32 of 35

This series is for beginners in which we explore python language along with how it is used in data science and do some exercises and some python related projects.

Up next

Day32-Set Methods

Set Methods 1. Joining Sets Sets in python more or less work in the same way as sets in mathematics. We can perform operations like union and intersection on the sets just like in mathematics. I. unio