A Complete Beginner-Level Python Course to Learn Data Science and Machine Learning
Day 3: Sets and frozen sets, comparison operators, the if-else statement, functions & Lambda functions
It is the third day of our journey to learn all the Python we need for Machine Learning and Data Science. All of my new code is linked to the previous code from the first and second parts of this series. You can find them below.
Day 3: Sets and Frozen Sets, Comparison Operators, the If-Else Statement, Functions, Lambda Functions
Sets
Definition
A set is an unordered collection of items. Every set element is unique (no duplicates) and must be immutable (cannot be changed). However, a set itself is mutable. We can add or remove items from it. Sets can also be used to perform mathematical set operations like union, intersection, symmetric difference, etc.
Purpose
A Set is an unordered collection data type that is iterable, mutable and has no duplicate elements. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set.
Importance
Because sets cannot have multiple occurrences of the same element, it makes sets highly useful to efficiently remove duplicate values from a list or tuple and to perform common math operations like unions and intersections.
Strengths
- The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set. This is based on a data structure known as a hash table. Since sets are unordered, we cannot access items using indexes as we do in lists.
- Because sets cannot have multiple occurrences of the same element, it makes sets highly useful to efficiently remove duplicate values from a list or tuple and to perform common math operations like unions and intersections.
- They help a lot when there is a need for this uniqueness of the elements that need to be processed.
- They help a lot when there is a need for this uniqueness of the elements that need to be processed.
The property that defines sets is the possibility to apply the methods of intersection, union, difference, and symmetric difference between them (like sets in mathematics I guess). Mind you cannot do these operations with lists or dictionaries (you have to convert them into sets beforehand).
Weaknesses
Since set items are not indexed, sets don’t support any slicing or indexing operations. Sets do not support indexing, slicing, or other sequence-like behavior. There are currently two built-in set types, set, and frozenset. The set type is mutable — the contents can be changed using methods like add() and remove().
Example 01
Task
create a simple set from {} and using the set function to add value to the set also use an update, discard and remove function on it.
Code
numbersSet={3.2,3.06,0.29,0.36,1}
rollNoList
newNumbersSet=set(rollNoList)
print(newNumbersSet)
type(newNumbersSet)
numbersSet.add(3)
print(numbersSet)
numbersSet.update({3,3,4})
numbersSet
numbersSet.update({2.2,2.3,3.7})
numbersSet
numbersSet.discard(1)
print(numbersSet)
numbersSet.remove(0.36)
print(numbersSet)
numbersSet.discard(1)
print(numbersSet)
numbersSet.remove(1)
Output
{1, 2, 3, 5, 6, 7}
set
{0.36, 0.29, 1, 3.06, 3.2, 3}
{0.29, 0.36, 1, 3, 3.06, 3.2, 4}
{0.29, 0.36, 1, 2.2, 2.3, 3, 3.06, 3.2, 3.7, 4}
{0.36, 0.29, 3.06, 3.2, 3, 4, 3.7, 2.2, 2.3}
{0.29, 3.06, 3.2, 3, 4, 3.7, 2.2, 2.3}
{0.29, 3.06, 3.2, 3, 4, 3.7, 2.2, 2.3}
KeyError
Traceback (most recent call last)
<ipython-input-113-f1792ffe8773> in <module>
----> 1 numbersSet.remove(1)
KeyError: 1
Frozen Sets
Definition
A frozen set is just an immutable version of a Python set object. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation. Due to this, frozen sets can be used as keys in Dictionary or as elements of another set.
Purpose
The frozenset() is an inbuilt function in Python which takes an iterable object as input and makes them immutable. Simply it freezes the iterable objects and makes them unchangeable.
In Python, frozenset is the same as set except its elements are immutable. This function takes input as an iterable object and converts them into an immutable object. The order of elements is not guaranteed to be preserved.
Importance
Their main ability that they are immutable makes them very important as you want to have a data set that if once is declared, no one can add something onto it.
Strengths
- A set cannot have mutable elements but frozen sets can.
- A set is mutable in nature and can be modified but frozen sets cannot be modified.
- A set cannot be used as a key in the dictionary but frozen sets can be used.
- A set cannot have set as an element, a frozen set can.
- The frozen set can be used as a dictionary key
Weaknesses
The major disadvantage of a frozenset is that since they are immutable, it means that you cannot add or remove values.
Example 02
Task
Use frozen set as an element of a set.
Code
#frozenset as an element of setS1 = frozenset([1,2,3,4])S2 = {S1}print(S2)
Output
{frozenset({1, 2, 3, 4})}
Example 03
Task
Use Frozen sets as a Dictionary
Code
#frozenset can be used as dictionary keyS1=frozenset([1,2,3,4])D1={S1:”1234"}print(D1)
Output
{frozenset({1, 2, 3, 4}): ‘1234’}
Comparison Operator & Logical AND OR NOT operator
Example 04
Task
Use different operators to check different conditions and their output
Code
5>66<815>=1515>=1415<=16"Umair" == "Usama""Umair" == "Umair""Umair" != "Usama"(3.06<4) or ("Umair" == "Usama")("Umair"=="Umair") and (5<6)
Output
False
True
True
True
True
False
True
True
True
True
If Statements
Definition
If statements are control flow statements which helps us to run a particular code only when a certain condition is satisfied. For example, you want to print a message on the screen only when a condition is true then you can use an if statement to accomplish this in programming.
Purpose
Python if Statement is used for decision-making operations. It contains a body of code which runs only when the condition given in the if statement is true. … When you want to justify one condition while the other condition is not true, then you use “if statement
Importance
If statement in Python tells the program what to do if the condition is true. In case the condition is false, the program just goes on to execute what comes after if statements
Strengths
- The major advantage of if-else statements is that they help us decide what to do if one of our expected output/decision gets changed. For example, if the user is logged in, show him the logout button; else, show him the login button.
- They help our code by stoping the crashing of our system if we did not get the desired result. We will simply print the message on the screen instead of throwing the same wrong data and getting errors.
- They help us better our code by applying certain conditions.
Weaknesses
The Weaknesses of the if-else statements is that if we have so many conditions to check or so many answers to check against the same conditions, then it will get really complicated for us to read the code and for the compiler to compile it.
If the number of if-else statements increases, it will overload the system and delayed the execution time.
Example 5
Task
Use if-else statement to check if the number is even or odd
Code
number=39if(number%2==0):print("{} is even.".format(number))else:print("{} is Odd.".format(number))
Output
39 is Odd.
Example 6
Task
Use if statement to check if the student’s age from the studentDictionary initializes above is greater than 18 or not.
Code
if((studentsDict['Student1']['age'])>18):print("{name} you can watch Horror Movie".format(name=studentsDict['Student1']['name']))
Output
Muhammad Umair you can watch Horror Movie
Loops in Python
Definition
Looping means repeating something over and over until a particular condition is satisfied.
A for loop in Python is a control flow statement that is used to repeatedly execute a group of statements as long as the condition is satisfied. Such a type of statement is also known as an iterative statement. Thus, a for loop is an iterative statement.
Purpose
The purpose of the loops is to reduce the amount of the repetitive task and also save the time
Importance
Loops are important in Python or in any other programming language as they help you to execute a block of code repeatedly. You will often come face to face with situations where you would need to use a piece of code over and over but you don’t want to write the same line of code multiple times.
Strengths
1. Easy to Read, Learn and Write
Python is a high-level programming language that has English-like syntax. This makes it easier to read and understand the code.
Python is really easy to pick up and learn, that is why a lot of people recommend Python to beginners. You need fewer lines of code to perform the same task as compared to other major languages like C/C++ and Java.
2. Improved Productivity
Python is a very productive language. Due to the simplicity of Python, developers can focus on solving the problem. They don’t need to spend too much time understanding the syntax or behavior of the programming language. You write less code and get more things done.
3. Interpreted Language
Python is an interpreted language which means that Python directly executes the code line by line. In case of any error, it stops further execution and reports back the error which has occurred.
Python shows only one error even if the program has multiple errors. This makes debugging easier.
4. Dynamically Typed
Python doesn’t know the type of variable until we run the code. It automatically assigns the data type during execution. The programmer doesn’t need to worry about declaring variables and their data types.
5. Free and Open-Source
Python comes under the OSI-approved open-source license. This makes it free to use and distribute. You can download the source code, modify it and even distribute your version of Python. This is useful for organizations that want to modify some specific behavior and use their version for development.
6. Vast Libraries Support
The standard library of Python is huge, you can find almost all the functions needed for your task. So, you don’t have to depend on external libraries.
But even if you do, a Python package manager (pip) makes things easier to import other great packages from the Python package index (PyPi). It consists of over 200,000 packages.
7. Portability
In many languages like C/C++, you need to change your code to run the program on different platforms. That is not the same with Python. You only write once and run it anywhere.
However, you should be careful not to include any system-dependent features.
Weaknesses
1. Slow Speed
We discussed above that Python is an interpreted language and dynamically-typed language. The line-by-line execution of code often leads to slow execution.
The dynamic nature of Python is also responsible for the slow speed of Python because it has to do the extra work while executing code. So, Python is not used for purposes where speed is an important aspect of the project.
2. Not Memory Efficient
To provide simplicity to the developer, Python has to do a little tradeoff. The Python programming language uses a large amount of memory. This can be a disadvantage while building applications when we prefer memory optimization.
3. Weak in Mobile Computing
Python is generally used in server-side programming. We don’t get to see Python on the client-side or mobile applications because of the following reasons. Python is not memory efficient and it has slow processing power as compared to other languages.
4. Database Access
Programming in Python is easy and stress-free. But when we are interacting with the database, it lacks behind.
Python’s database access layer is primitive and underdeveloped in comparison to popular technologies like JDBC and ODBC.
Huge enterprises need smooth interaction of complex legacy data and Python is thus rarely used in enterprises.
5. Runtime Errors
As we know Python is a dynamically typed language so the data type of a variable can change anytime. A variable containing an integer number may hold a string in the future, which can lead to Runtime Errors.
Therefore Python programmers need to perform thorough testing of the applications.
Example 7
Task
Use for loop to print Fibonacci series until the limit.
Code
firstNumber=0secondNumber=1numberThree=0limit=10fibList=[0,1]for i in range(1,limit):numberThree=firstNumber+secondNumberfirstNumber=secondNumbersecondNumber=numberThreefibList.append(numberThree)
Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Example 8
Task
Use While Loop to find out that if the string is palindrome or not
Code
givenString="radar"i=0check=Falsewhile(i<(len(givenString)/2)):check=((givenString[i]==givenString[(len(givenString)-1)-i]))if(i!=0 and check==False):print("{string} is a not palindrom".format(string=givenString))breaki=i+1if(check==True):print("{string} is a palindrom".format(string=givenString))
Output
radar is a palindrom
Functions
Definition
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
Purpose
A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.
Importance
You use functions in programming to bundle a set of instructions that you want to use repeatedly or that, because of their complexity, are better self-contained in a sub-program and called when needed. That means that a function is a piece of code written to carry out a specified task.
Strengths
- Reducing duplication of code
- Decomposing complex problems into simpler pieces
- Improving the clarity of the code
- Reuse of code
- Information hiding
Weaknesseses
A function is the wrapped piece of code that is used to perform a specific function when needed. The only Weaknesses of it is if developers use them wrongly.
Example 9
Task
Use functions to create a function that prints the values of a tuple.
Code
def printResult():i=0while(i <(len(studentsResult))):print("Name:{} CGPA:{}".format(studentsResult[i][0],studentsResult[i][1]))i=i+1printResult()
Output
Name:Muhammad Umair CGPA:3.06Name:Hamdad Ijaz CGPA:2.8Name:Muhammad Abdullah Tahir CGPA:2.7
Example 10
Task
Use functions to create a function that checks if the string is palindrome or not.
Code
def checkPalindrom(givenString):i=0check=Falsewhile(i<(len(givenString)/2)):check=((givenString[i]==givenString[(len(givenString)-1)-i]))if(i!=0 and check==False):print("{string} is a not palindrom".format(string=givenString))return Falsebreaki=i+1if(check==True):print("{string} is a palindrom".format(string=givenString))return TruecheckPalindrom("radar")
Output
radar is a palindromTrue
Example 11
Task
Use functions to create a function to print the Fibonacci series taking the limit as an argument.
Code
def printFibonachi(limit):firstNumber=0secondNumber=1numberThree=0fibList=[0,1]for i in range(1,limit):numberThree=firstNumber+secondNumberfirstNumber=secondNumbersecondNumber=numberThreefibList.append(numberThree)print(fibList)return fibListprintFibonachi(15)
Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610][0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
Lambda Functions
Definition
A lambda function is a single-line function declared with no name, which can have any number of arguments, but it can only have one expression. Such a function is capable of behaving similarly to a regular function declared using the Python’s def keyword. Often times a lambda function is passed as an argument to another function.
Purpose
We use lambda functions when we require a nameless function for a short period of time. In Python, we generally use it as an argument to a higher-order function (a function that takes in other functions as arguments). Lambda functions are used along with built-in functions like filter() , map() etc.
Importance
A lambda is part of a very important abstraction mechanism which deals with higher-order functions. To get a proper understanding of its value, please watch high-quality lessons from Abelson and Sussman, and read the book SICP.
Strengths
- The code is simple and clear.
- No additional variables are added.
- Save Memory by declaring and initializing fewer variables.
Weaknesseses
- Lambda expressions are a strange and unfamiliar syntax to many Python programmers.
- Lambda functions themselves lack names and documentation, meaning that the only way to know what they do is to read the code.
- Lambda expressions can only contain one statement, so some readable language features, such as tuple unpacking, cannot be used with them.
- Lambda functions can often be replaced with existing functions in the standard library or Python built-in functions.
Example 12
Task
Use a lambda function to create a square function and create a list of 10 numbers and apply the lambda function of square and cube on it.
Code
square=lambda number:number**2squareList=[]numberList=list(range(1,10))for number in numberList:squareList.append(square(number))[(lambda x: x**3)(x) for x in range(10)]
Output
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
More content at plainenglish.io