Log in to save your progress.
<< Previous
Home
Note! The window is too narrow to use Pythonlab.dev. Use a device with a keyboard!

Reference

Click on a function to read more.
Basics part 1
Syntax
Short description
break
break interrupts code that is repeated
continue
continue interrupts a repetition and starts the next
elif
elif is a combination of else and if
else
else can be used last in an if-statement
float()
Converts to type float (decimal number)
if
if controls the code to do different things depending on a condition
input()
Receives input from the user
int()
Converts to type int (integer)
randint()
Generates a random integer
round()
Rounds a number
str()
Converts to type string
while
while is used to repeat code
Basics part 2
Syntax
Short description
abs
Absolute value
append
Adds an element to a list
def
Defines a function
for
for is used to repeat code
len
Returns the number of elements in an object
max
Returns the largest element
min
Returns the smallest element
pop
Removes an element from a list
return
Returns data from a function
sum
Sums the elements in an object

Sets

In this section you will learn to

What is a set?

Sets are a common concept in mathematics. A set is a collection of elements. Duplicates are not allowed. If we try to add an element that already exists in the set, nothing happens, the set remains the same.

In Python, a set is called set, which is also the English word for set. The most common functions for sets are to add elements, remove elements and check if an element exists in the set.

If only the most common functions are used, the similarities between sets and dictionaries are great. For sets in Python, however, there are specialized functions that are useful specifically for sets. On two sets, for example, we can use the union (combine) and the intersection (see which values are in both sets). For readability, it is recommended to use a set if it is sufficient.

Common functions

Just like for dictionaries, there are two common ways to create a set. See example below.

Example

Create a set with curly braces.

my_set = {1, 2, 3}

Example

Create an empty set and then add elements one by one.

my_set = set()
my_set.add(1)
my_set.add(2)
my_set.add(3)
my_set.add(3) #nothing happens, 3 already exists.
  

To remove an element from a set, there are among others set.pop() and set.remove(element). The function pop returns the element that is removed and can be used if it does not matter which element is picked out of the list.

Use remove to remove a specific element. Note that remove gives Keyerror if the element you are trying to remove does not exist. If you don't want that, there is set.discard(element) which works even if the element is not in the set.

Example

Remove an element with pop() and remove(element).

pets = {'Cat', 'Dog', 'Goat', 'Zebra'}
pets.remove('Zebra')
removed = pets.pop()
  

To see if an element exists in the set, in is used just like for keys in a dictionary.

Example

See if an element exists in the set with in.

pets = {'Cat', 'Dog', 'Goat', 'Zebra'}
if 'Dog' in pets:
    print('Dog is in the pet set.')
  

Login or create an account to save your progress and your code.

What does the code do?

Read the code below and try to figure out what the program prints. Run the program after you answer and see if you were correct.

-- Output from your program will be here --

Question: What will the program print?

-61
61
63
123

Duplicates and set()

There is a simple trick to count the number of unique elements in a list or a tuple. If the list or tuple is converted to a set, all duplicates are automatically removed. Just remember that the order of the elements is not preserved.

Example

We use set() on a list to remove all duplicates.

my_list = [3, 7, 2, 3, 6, 8, 3]
my_set = set(my_list)
number_of_unique_elements = len(my_set) # 5
number_of_duplicates = len(my_list) - len(my_set) # 2
  

Iterate over a set

If we want to iterate through the entire set element by element and at the same time keep the set intact, we can easily do so with for.

Example

Iterate over a set. The set looks the same afterwards.

racketlon = {'bordtennis', 'badminton', 'squash', 'tennis'}
for sport in racketlon:
    print(sport)
  

If we instead want to extract one element at a time until the set is empty, we can use while set: and set.pop() as the example below shows. The while-statement while set: continues until the set is empty. It is therefore important that the set is guaranteed to eventually become empty, otherwise it will be an infinite loop.

Example

Extract one element at a time from a set until the set is empty.

my_set = {'Carina', 'Per-Goran', 'Elisabeth', 'Ola'}
while my_set:
    name = my_set.pop()
    print('Extracted name', name)
  

Login or create an account to save your progress and your code.

Change the code

The program below receives a number of strings from the user and puts them in a list. Use what you have learned about sets to calculate how many unique elements the user has entered. Save the number in the variable unique_elements.

-- Output from your program will be here --
Status
You have finished all tasks in this section!
🎉