DEV Community

Cover image for Reviewing Python - Fundamentals
Mark Abeto
Mark Abeto

Posted on • Updated on

Reviewing Python - Fundamentals

Hi Guys Good Day!

It's been almost two months that I haven't posted anything because
I was busy studying and playing games haha. Ok, mostly my articles are about JavaScript or TypeScript so I'm gonna go to a different area specifically Python. Python is my favorite programming language not because it's the most popular programming language right now or it has a lot of uses in different areas in Software Development like in Web Development, Machine Learning or Data Science but because it's the language that I used that help
me graduate college. I loved it since the first time using it. I love the syntax, I love how easily you can learn it's basics and fundamentals and how you can easily write lesser code with it compared to other languages. Honestly, It gives me hope when there were hard times in my last semester in college that I thought that I was not able to graduate because it was hard to manage the time between my thesis and other subjects but Thanks to Python I graduated. It's been almost two years that I haven't programmed in Python so I started learning it again so here's what I learned again.
So Let's get started.

Variables

Variables are placeholders for values. Variables are use to keep track or remember data in our program.
Instead of remembering a specific value we remember the variable that holds that value. Making in variables in Python is straightforward.

my_secret_num = 1
myName = "Mark"
isDone = False
_ = None

# A variable name must not start with a number or a special character except underscore "_"

0_1 = 1 # raises a Syntax Error
dollar$= "$ss" # raises a Syntax Error
@_2 = 1 # raises a Syntax Error

Enter fullscreen mode Exit fullscreen mode

Indentation

What makes Python unique from other languages is that it has strict indentation rules, sometimes it's a pain in the ass doing it manually but if you're using an IDE then I think that IDE maybe has some option to configure the number of spaces to use. The standard number of spaces to use in Python is 4. Indentation makes your code cleaner and more readable. An indentation starts after a colon :.

if True:
    print("Indentation Rocks") # This statement has 4 spaces before it.

i = 0
while True:
    if i == 2: # This statement has 4 spaces before it.
        break # This statement has 8 spaces before it.
    else:       # This statement has 4 spaces before it.
        i += 1 # This statement has 8 spaces before it.

def func():
    pass  # This statement has 4 spaces before it.

for num in [1,2,3]:
print(num) # This raises an Error SyntaxError: expected an indented block

Enter fullscreen mode Exit fullscreen mode

Data Types

Every value that we assign to a variable holds a value and that value has a specific data type. Every data type can be used in any situation but in a certain situation or problem, there is always a more suited data type to use. Python has a number of data types like Boolean, Strings, Numbers, , Lists, Dictionaries, Tuples, Sets, Files and None.

my_first_name = "Mark" # String
my_fav_num = 21 # Number - Integer
my_fav_float_num = 21.0 # Number - Float

is_current_year_odd = False # Boolean - True | False
wish_list = ["new video card","new monitor","new keyboard"]  # List
language_profiencies = { # Dictionary
     "Python" : 6.5,
     "JavaScript" : 8.5
     "TypeScript" : 7
}
cant_change_this = ("Global Warming","is","Real") # Tuple
nums = {1,2,3,4,5,1} # Set
sample_file_data = open("path/to/file.txt","a") # File
Enter fullscreen mode Exit fullscreen mode

Operations and Flow Control

There's a lot of operations that we can use in Python.

Most of this is used for updating a certain value by using current value and updating it. I mostly used the first half in this table because I haven't faced a problem that required using the second half.

Augmented Assignment Operators

Shorthand Equivalent
a += b a = a + b
a -= b a = a - b
a *= b a = a * b
a /= b a = a / b
a //= b a = a // b
a %= b a = a % b
a **= b a = a ** b
a &= b a = a & b
a ^= b a = a ^ b
a >>= b a = a >> b
a <<= b a = a << b

Math Operators

Math Operators are mostly used in Numbers in Python.

Operation Operator Example Result
Exponent ** 2 ** 3 8
Remainder % 5 % 3 2
Floor Division // 4 // 3 1
Division / 2 / 2 1
Multiplication * 2 * 2 4
Subtraction - 1 - 2 -1
Addition + 1 + 2 3

All of these operations can only be used on a value with a type of Number. But some of these operations can be used in other types other than Numbers.

print("Hello " + "World") # This prints Hello World
# string concatenation

print("Hello" * 3) # This prints HelloHelloHello
# string repetition

print([1,2,3] + [4,5]) # This prints [1,2,3,4,5] 
# + combines both list

print([1] * 3) # This prints [1,1,1]
# * list repetition.

Enter fullscreen mode Exit fullscreen mode

Boolean Operators

Boolean Operators are mostly used in if conditions or Flow Control which we will talk about later.

and operator Result
False and False False
False and True False
True and False False
True and True True
or operator Result
False or False False
False or True True
True or False True
True or True True
not operator Result
not True False
not False True

Comparison Operators

Comparison Operators are used to comparing two values which will evaluate into a single Boolean value.

Operation Operator Example Result
Greater than > 5 > 2 True
Less than < 5 < 2 False
Greater than or equal to >= 4 >= 3 True
Less than or equal to <= 4 <= 3 False
Not Equal != 2 != 2 False
Equal == 2 == 2 True

if, elif, else statements.
Sometimes we want our code to run based on a certain condition or conditions. That's where if, elif, else statements comes to play. The syntax for these three is shown below.

is_done = True

if is_done:
   print("The job is done") # This will be printed because the variable "is_done" is True
else:
   print("The job is not done") # This will not print 

Enter fullscreen mode Exit fullscreen mode

The else statement will run will only run if the if statement's condition is not True. If we want multiple conditions we can use the elif statement. The elif statement will be checked if the previous if statement or previous elif statements evaluated to False.

my_grade = "B"

if my_grade == "A":
    print("Amazing")
elif my_grade == "B":
    print("Very Good")  # This will be printed
elif my_grade == "C":
    print("Good")
elif my_grade == "D":
    print("Bad")
elif my_grade == "E":
    print("Very Bad")
else:
    print("Failed")

Enter fullscreen mode Exit fullscreen mode

In the above example, it prints <>Very Good because the variable my_grade has a value of "B" and it ignores the rest of the elif statements and else statement.

Loops
Python has two main mechanisms for repeating a block of code over and over again or in a specific number of times.
while and for loops.

while loops are used for repeating a block of code while a certain condition is True. The syntax for a
while loop is shown below.


count = 0
while count < 5:
    print(count)
    count += 1

Enter fullscreen mode Exit fullscreen mode

In this example, the loop will continue until the count variable will have a value of 5. Because our condition says repeat the block of code while the count is less than 5 so in the block of code we add a value of 1 to count.

for loops, on the other hand, execute a block of code in a specific number of times. The syntax for a for loop is shown below.


avengers = ["Iron Man", "Captain America","Thor", "Hulk", "Black Widow", "Hawkeye"]

for avenger in avengers:
    print(avenger) 

Enter fullscreen mode Exit fullscreen mode

In this example, we assign the variable name avenger for each of the six values on the avengers List. Mostly it starts from the 0 index up until to the last. In every iteration, the avenger variable will hold a different item in the List.

If you want to get the index rather than a value in the List. You can use the range and len functions.

The range function has three parameters range(start,stop,step). The start has a default value of 0 and step has a default value of 1. If the start and step are not provided then whatever value provided in range function will be the stop and should be an integer.

print(range(5)) # This prints range(0,5)
print(range(0,5,1)) # This is equivalent in the print statement above
print(range(0,5)) # This is equivalent in the print statement above

# We can convert the return value of the range function into a List. Using the list function

print(list(range(5))) # This prints [0,1,2,3,4] does not include the stop

Enter fullscreen mode Exit fullscreen mode

The len function returns the number of items in the container. We can use it in Lists, Strings, Tuples, Sets, and Dictionaries.

print(len("abc")) # This prints 3. The number of characters in the String
print(len([1,2,3,4,5])) # This prints 5. The number of values in the List
print(len((1,2,3,4))) # This prints 4. The number of values in the Tuple
print(len({1,2,3,3})) # This prints 3. The number of values in the Set
print(len({"a":"eyy","b":"bee","c":"si"})) # This prints 3. The number of keys in the Dictionary
Enter fullscreen mode Exit fullscreen mode

So the range and len functions are a good combination for getting indexes in Lists.

for index in range(len(avengers)):
    print(f"{index} - {avengers[index]}") # This prints the index and the corresponding value at that index in each iteration
Enter fullscreen mode Exit fullscreen mode

There are statements that are only valid inside loops. Those are break and continue statements.

The break statement is used to stop or exit the Loop right away.

i = 0
while True:
    count += 1
    if count == 3:  # When the value of count is 3. This loop will exit
        break
    else:
        print(count)

for avenger in avengers:
    if avenger == "Thor":  # When the value of avenger is Thor. This loop will exit
        break
    else:
        print(avenger)
Enter fullscreen mode Exit fullscreen mode

The continue statement will skip the current iteration and continue to the next one. It will go back to the loop declaration before continuing to the block of code.

i = 0
while True:
    count += 1
    if count == 3:  # Will not print 3
        continue
    else:
        print(count)

for avenger in avengers:
    if avenger == "Thor":  # Will not print Thor
        continue
    else:
        print(avenger)
Enter fullscreen mode Exit fullscreen mode

Boolean

Boolean type has only two values True and False. When we use comparison operators and boolean operators between values they evaluate to a single boolean value. Boolean values are used for if conditions , while loops and
etc.

is_absent = False
my_fav_num = 5

print(is_absent) # This prints False
print(my_fav_num > 1) # This True because it compares if 5 is greater than 1 which evaluates to True
print(True and False) # This prints False
print(True or False) # This prints True
print(not False) # This prints True

if is_absent:
    print("Mark is present")  # This will not be printed because is_absent is False
else:
    print("Mark is absent")  # This will be printed

while True:  # This is an example of an infinite loop
    print("This will not stop")  # Press Ctrl+C to Stop

Enter fullscreen mode Exit fullscreen mode

True and False are just 1 and 0 respectively. They don't have the same type but they have the same value but have different printing logic.

print(True == 1) # This prints True
print(False == 0) # This prints True

Enter fullscreen mode Exit fullscreen mode

Strings

Strings are obviously values for texts. Working with Strings in Python is relatively easy and fun. We can make a string with either double-quote " or a single-quote '. If a string starts with a single-quote
it also must end with a single-quote. If it starts with a double-quote and must end with a double-quote.

my_name = "Mark"

my_favorite_language = 'Python'

my_favorite_book = 'The Sum of all Fears"
# This will raise a SyntaxError because it starts with a single-quote but ends with a double-quote
Enter fullscreen mode Exit fullscreen mode

We can access a specific value in the String using an index. The index is the position of that character (a character is a single string like "a") in the String. An index is an integer that starts with 0,1,2,3 until we end up to the last character in the String which has an index of the length of the String minus 1. We can also use negative numbers when indexing -1 is the last index in the String, -2 refers to the second to the last index and so on.

String - 'Mark' M a r k
Positive Indexing 0 1 2 3
Negative Indexing -4 -3 -2 -1

first_letter = my_name[0] # returns the first character in my_name variable which is "M"

print(first_letter) # This will print "M"

first_letter = my_name[-4] # returns the first character in my_name variable which is also "M" using negative-indexing

print(first_letter) # This will print "M"
Enter fullscreen mode Exit fullscreen mode

We can use a great functionality called slicing in Strings in Python. slicing is extracting a specific portion of data in a given data type. We can specify where we start extracting, where we want to end the extract or the number of steps we want to. It looks like this my_name[0:4:1] in this example my_name is a string variable that holds a value of "Mark", slicing starts by using square brackets, the 0 is our starting point, the 4 is the endpoint but not included, and the last one 1 is our step, the step we make from the start to end.

guess_my_value = my_name[0:4:1]
# It will extract the portion of the characters from index 0 to index 4 but not including, with a step of 1
# so it extract 'M', 'a', 'r', 'k' with an index of 0,1,2,3 respectively. The step has a default value of 1.

print(guess_my_value) # This will print "Mark"

print(my_name[0:4]) # This will still print "Mark"

print(my_name[:]) # This will still print "Mark"

print(my_name[0:]) # This will still print "Mark"

Enter fullscreen mode Exit fullscreen mode

Note: Strings are immutable which means that we cannot or delete change a specific character in that String unless
you assign that variable that holds the string with a new value.


my_name[0] = "A" # This will raise a TypeError 'str' object does not support item assignment
my_name = "Polo" # This assigns a new value for my_name
print(my_name) # This will print "Polo"


Enter fullscreen mode Exit fullscreen mode

Strings has many, many methods that can help with our basic problems. Most of these methods returns a new string and does not mutate the original String.

my_name = "Mark"

print(my_name.upper()) # This prints "MARK"
# The "upper" method returns a new string version as all in uppercase

print(my_name.lower()) # This prints "mark"
# The "lower" method returns a new string version as all in lowercase

print(my_name.islower()) # This prints False
# The "islower" method returns a Boolean indicating if the String contains all lowercase letters
# it returns True if all letters are lowercase else return False

print(my_name.isupper()) # This prints False
# The "isupper" method returns a Boolean indicating if the String contains all uppercase letters
# it returns True if all letters are lowercase else return False

print(my_name.isalpha()) # This prints True
# The "isalpha" method returns a Boolean indicating if all characters in the String 
#  are alphabetic  it returns True else it returns False

print(my_name.isdigit()) # This prints False
# The "isdigit" method returns a Boolean indicating if all characters in the String
# are numbers it returns True else it returns False

print(my_name.index("ark")) # This prints 1
# The "index" method searches a substring in String and returns the starting Index
# of the substring else this method raises a ValueError.

print("a,b,c,d".split(",")) # This prints ["a","b","c","d"]
# The "split" method obviously splits the String with parameter separator and returns a
# list of all strings. It also has a second parameter which is a number that indicates 
# the number of splits we want.

print(my_name.startswith("Ma")) # This prints True
# The "startswith" method returns a Boolean indicating if the String
# starts with a certain substring else it returns False     

print(my_name.startswith("rc")) # This prints False
# The "endswith" method returns a Boolean indicating if the String
# ends with a ceratin substring else it returns False   
Enter fullscreen mode Exit fullscreen mode

There are still many methods that I haven't discuss in this example, you all can try it yourself.

Numbers

The Numbers data type has lots of types in Python. Integers, Floating-point numbers, Octal, Hex, Binary, Complex Numbers, Sets (which will talk about later), Boolean, Decimal and Fraction. Numbers is not a single type like Strings or Lists but they are several types that are related to each other.

import fractions
import decimal

my_num = 5 # Integer
pi = 3.14 # Floating-point number
ten = 0o012 # Octal
x = 0x123 # Hex
two = 0b010 # Binary
unique_nums = {1,2,3,2,3} # Sets
is_done = True # Boolean
one_and_a_half = fractions.Fraction(1/2)  # Fraction
one_over_three = decimal.Decimal(1/3) # Decimal
Enter fullscreen mode Exit fullscreen mode

Ok, I'm not gonna talk a lot of all these types because we mostly use Integers and Floats.

If you want to use Strings with Integers or Floats. You have to convert first that number using the str function before using it.

print(str(2) + "is two")
print(str(3.0) + "is three")
print(4.1+ "is four point one") This raises a TypeError: unsupported operand type(s) for +: 'float' and 'str'
Enter fullscreen mode Exit fullscreen mode

You're wondering why the Boolean type is related in the Numbers Type. Just as I said earlier
the Boolean values True and False are just 1 and 0 respectively they just different printing logic.

print(True == 1) # This prints True
print(False == 0) # This prints True
print(isinstance(True,int)) # This prints True
Enter fullscreen mode Exit fullscreen mode

While Sets has some mathematical operations using certain operators and methods. We will talk about Sets later.

Lists

Lists are values that acts as a container for other values. It can hold multiple values of the same type or multiple values of any type. It's called Arrays in other programming languages. We can declare a List using the square brackets []. We can put values in the List and separate them using comma , [1,2,3,4,5].

numbers = [1,2,3,4,5]
Enter fullscreen mode Exit fullscreen mode

We can access a specific value in the list using an index. The index is the position of that value in the List. An index is an integer that starts with 0,1,2,3 until we end up to the last item of the List which has an index of the length of the List minus 1. We can also use negative numbers when indexing -1 is the last index in the list, -2 refers to the second to the last index and so on. Same as Strings, Lists has positive and negative indexing.

one = numbers[0] # numbers[0] holds the value of 1in the List
two = numbers[1] # numbers[1] holds the value of 2 in the List
five = numbers[-1] # numbers[-1] holds the value of 5 in the List

# We can get the length of the array using the "len" method. We only pass the name of the variable that holds the List.

len_of_numbers = len(numbers) # len(numbers) returns 5

# If we access an index that is more than the number of values in the List
# you will get an IndexError

guess_this_number = numbers[1000] # This will raise the IndexError

Enter fullscreen mode Exit fullscreen mode

If you want to check every item in a List. You can use for Loops.

avengers = ["Iron Man","Captain America","Thor","Hulk","Black Widow","Hawkeye"]

for avenger in avengers: 
      print(avenger) # prints every avenger each in a new line

# If you want to use the index instead of the value
# we can also use that using for loops with the help of "range" and "len" functions

for index in range(len(avengers)):
      print(index) # prints the index each in a new line

# Tip: Instead of checking the length of a List in a condition
# just use the list instead

data = ["one"] 

if len(data):
    print("This will be printed.")

# Use this instead

if data:
    print("This will be printed.")

Enter fullscreen mode Exit fullscreen mode

Just like Strings we can use slicing in Lists.

l = [1,2,3,4,5]

# list[start:stop:step] 

len_l = len(l) # has a value of 5
half = len_l//2

first_half = l[0:half] # l[0:half] will evaluate to l[0:2] is also equivalent to l[:2]

print(first_half) # This will print [1,2]

second_half = l[half:len_l] # l[half:l] will evaluate to l[2:5] is also equivalent l[2:] 

print(second_half) # This will print [3,4,5]

odd_nums = l[0:len_l:2] 
#  l[0:len_l:2] will evalute to l[0:5:2] the 0 our start, the 5 is our stop and the step is 2 
#  l[0:5:2] is also equivalent to l[0::2] or l[::2]

print(odd_nums) # This will print [1,3,5]

reverse_l = l[::-1] 
#  l[::-1] This reverse the start and stop meaning we will start at the last item and stop 
# with the first item. [::-1] is also equivalent to l[len(l)::-1]

print(reverse_l) # This will print [5,4,3,2,1]

Enter fullscreen mode Exit fullscreen mode

Lists has many methods that make our life easier.


avengers.append("Ant-Man") 
# The "append" method add a new item at
#  the end of List

avengers.count("Iron Man") # returns 1
# The "count" method counts how many times
#  the value passed appears

avengers.extend(["Doctor Strange","Spiderman","Black Panther"])
# The "extend" method adds all items 
# passed at the end of the List. The parameter passed must be an Iterable object.

avengers.index("Captain America") # returns 1
# The "index" method returns the first index of the value passed.
# If the value does not exist this method raises a ValueError.

avengers.insert(0,"Captain Marvel")
# The "insert" method obviously inserts a value 
# at a specified index but does not replace the
#  current value at that position.

avengers.append("Thanos")
avengers.remove("Thanos") # returns 1
# The "remove" method obviously removes the first occurence of the value passed.
# If the value does not exist this method raises a ValueError.

avengers.reverse()
# The "reverse" method reverses the position of each item in the List.
# If the List looks like this my_list = [1,2,3]
# then we use l.reverse()
# then my_list would look like this [3,2,1]

avengers.pop()
# The "pop" method removes the last item in the List and returns it.
# We can specify the index to remove in pop method as a parameter
# If the index is not valid or if the List is empty this method raises an 
# IndexError.

Enter fullscreen mode Exit fullscreen mode

Tuples

Tuples is like a List but the difference between them is that Lists are mutable which means
we can change or delete the values inside a List but with Tuples are immutable which means
we cannot change or delete any values on a Tuple. We can make a Tuple using parentheses.

my_favorite_numbers = (1,21,19)

# If you only assign one value in the Tuple without using a comma 
# Python will treat that as an expression and in turn that variable
# will not be a tuple instead will the first item in the parentheses

my_secret_nums = (666) 

print(my_secret_nums) # will print 666 instead of (666)

my_new_secret_nums = (666,)

print(my_new_secret_nums) # prints (666,)
Enter fullscreen mode Exit fullscreen mode

Tuples is almost like a List we can use slicing, concatenation, we can access a value using an index, we can tuple repetition using the * operator. But we cannot add or change any value in a Tuple. A Tuple has only two methods index, and count.

secret_hero_real_names = ("Bruce Wayne","Steve Rogers","Clark Kent","Peter Parker")

secret_hero_real_names.count("Bruuce Wayne") #returns 0
secret_hero_real_names.count("Peter Parker") #returns 1 
secret_hero_real_names.index("Steve Rogers") # returns 1
Enter fullscreen mode Exit fullscreen mode

Dictionaries

Dictionaries are also a container for data like Lists but unlike Lists which we access a specific value in List with an index in Dictionaries we access a value using a key or property which in turn holds a value and items in Dictionaries are unordered while in Lists are ordered_. We can make a __Dictionary using curly braces {}.


books_currently_reading_bookmark = {
   "Angel & Demons" :  484,
   "Da Vinci Code": 100
}

# We can use a key with a type of "string","integer" or "tuples" in Dictionaries

d = { 1 : "one" }
print(d[1]) # prints "one"

d1 = { (1,2,3,4,5,6,7,8,9,10): "one-ten"}

print(d[(1,2,3,4,5,6,7,8,9,10)]) # prints "one-ten"

#We cannot use a type of "dictionary" or "list" as a key in Dictionaries

d2 = { [1,2,3] : "one-three" } # This will raise a TypeError : unhashable type: 'list'
Enter fullscreen mode Exit fullscreen mode

We can add a new key-value pair anytime in a dictionary.

letters_sounds = {}

letters_sounds["a"] = "eyyy"
letters_sounds["b"] = "bee"

print(letters_sound) # prints {'a': 'eyyy', 'b': 'bee'}
Enter fullscreen mode Exit fullscreen mode

If we check a key that does not exist in a dictionary. It will an error.

print(letters_sounds["c"]) # This will raise a KeyError which means that key "c" does not exist in the letters_sounds Dictionary.
Enter fullscreen mode Exit fullscreen mode

We can use the in operator or get method in Dictionaries
to check if a key exists in a Dictionary.

if "c" in letters_sounds: # Check if "c" exists
    print(letters_sounds["c"])
else:
   print("letters_sounds does not have a 'c' key")


print(letters_sounds.get("c") == None) # prints True
# The get method has a second parameter which is the default value 
# that will be used if the key does not exist in the Dictionary

print(letters_sounds.get("c",0)) # prints 0
Enter fullscreen mode Exit fullscreen mode

Dictionaries has many useful methods that can help some problems when dealing with Dictionaries.

new_letters_sounds = {
      "a": "ayy",
      "c" : "si"
}

letters_sounds.update(new_letters_sounds) 
# The "update" method adds or updates new keys in the dictionary it accepts 
# an Iterable type as a parameter or the source

letters_sounds.setdefault("c","sii") 
# The "setdefault" method add a new key and a default value in the dictionary
# if the key doesn't exist in the dictionary, if it exists it returns the value of that key

for key in letters_sounds.keys():
    print(key) # This prints "a", "b" and "c" respectively each in a new line
# The "keys" method returns all keys in the dictionary. This does not return a list.
# Instead it returns a set-like object.

for val in letters_sounds.values(): 
    print(val) # This prints "ayy", "bee" and "si" each in a newline
# The "keys" method returns all keys in the dictionary. This does not return a list.
# Instead it returns a set like object.

# If you want to access the key and the value in a loop.
# You can use the "items" method.
for key, value in tuple(letters_sounds.items()):
    print(f"{key}:{value}") # This prints "a:ayy", "b:bee" and "c:si" respectively each in a newline
# The "items" method returns the key and value in a set like object.

letters_sounds.pop("c")
# The "pop" method removes a key and its value in the Dictionary.
# If the key does not exist this raises a KeyError.

letters_sounds.clear()
# The "clear" method removes all the keys and values in the Dictionary.
Enter fullscreen mode Exit fullscreen mode

Sets

Sets are also containers just like Lists, Dictionaries and Tuples. The difference is that Sets are onordered collection, are immutable (the Set itself is mutable but the values must be immutable) like Tuples and holds only unique values. Sets are declared using curly brackets {} or the set function and also Sets look like Dictionaries the difference again is that Sets don't have keys.

nums = {1,2,3,4,3,4}
nums_2 = set([1,2,3,4,4,5,5]) 
print(nums)  # This prints {1,2,3,4} because Sets only holds unique values.

print(nums_2) # This prints {1,2,3,4,5}
Enter fullscreen mode Exit fullscreen mode

Because Sets are onordered we can't access a specific value. It has no indexing functionality like Lists and Tuples.


print(nums[0])
# This raises a TypeError: 'set' object does not support indexing.
Enter fullscreen mode Exit fullscreen mode

Even though Sets are called immutable it has methods that can change
or remove a specific value from the Set.

nums.add(4) 
# The "add" method adds a new value in Set if it does not 
# already exist. If already exists this method does nothing.

nums.remove(1)
# The "remove" method removes a specific value from the Set.
# If the value does not exist it raises a KeyError.

nums.clear()
# The "clear" method obviously removes all the values present
# in the Set.
Enter fullscreen mode Exit fullscreen mode

We can use certain operations in Sets that are not available in other types.

s1 = {1,2,3}
s2 = {3,4,5,6}

print(s1 | s2)  # This prints {1,2,3,4,5,6} 
# This operation is called "union" it combines both sets and returns a new set.
# It also have a equivalent method on sets called "union" suprise, suprise.
print(s1.union(s2))  # Also prints {1,2,3,4,5,6} 

print(s1 & s2) # This prints {3}
# This operation is called "intersection" it finds the common elements in both sets and returns it in a set.
# It also have a equivalent method on sets called "intersection" suprise, suprise.
print(s1.intersection(s2))  # Also prints {3}

print(s1 - s2)  # This prints {1, 2}
# This operation is called "difference" it finds the difference between the first Set and the second Set and returns a new Set.
# So in this example it calculates what elements "s1" has that "s2" does not have.
# It also have a equivalent method on sets called "difference" suprise, suprise.
print(s1.difference(s2)) # Also prints {1,2}

print(s1 ^ s2) # This prints {1,2,4,5,6}
# This operation is called "symmetric_difference" it finds the elements that are not common between the two sets and returns it as a Set.
# So in this example it calculates what unique elements between "s1" and "s2" has and returns it.
# It also have a equivalent method on sets called "symmetric_difference" suprise, suprise.
print(s1.symmetric_difference(s2)) # Also prints {1,2,4,5,6}
Enter fullscreen mode Exit fullscreen mode

Watch out for my next part of this post about Reviewing Python it will involve Handling Exceptions, Functions, List, Tuples,Dictionary and Set Comprehensions , Classes and Modules.

Thanks guys for reading this post.

Have a Nice Day 😃!.

Top comments (4)

Collapse
 
cdanielsen profile image
Christian Danielsen

Nice primer.

Small correction: In the 'or operator' table of the 'Boolean Operators' section, looks like there might be a copy-paste typo from the 'and operator' table above it (e.g. should be False or False, etc.)

Collapse
 
macmacky profile image
Mark Abeto

Thanks 😁 for pointing that one out.

Collapse
 
3cho0 profile image
3cho0

You should almost never use a counter in a python for-loop, use range or enumerate instead.

Collapse
 
davilopez profile image
David López

Using enumerate or range is definitely way more pythonic, however, in this example, I will agree with the author that s more understandable for people coming from other languages.