Classes and Objects in Python OOP

Hello pupil! We hope you are doing well with object-oriented programming with Python. OOP is an extremely important topic in programming, and the good thing about Python is that the concept of OOP can be implemented in it. In the previous lecture, we made a basic introduction to all the elements that are used in the OOP, and right now, we are moving forward with the detail of each concert with examples. The imperative nature of the OOP is useful for us because it uses the statements to change the programming state, and in this way, the working of the code becomes easy and effective. To use the applications of Python, the imperative nature of OOP will give us the tools we need to get the perfect results by using our creativity. We will prove this in just a bit, but here are the highlights of the topics that will be discussed. 

  • How can you describe the OOP by using an example?

  • Why are classes important in OOP?

  • Discuss the example and syntax of code when we use classes in OOP.

  • What are objects?

  • Give us an example where multiple objects are made if one class and the information are given by the user.

  • Discuss the basic features of objects in OOP.

  • How do you classify the attributes of objects?

  • What are the behaviours in OOP?

All of these are important to learn so pay attention to each and every concept and if you have any confusion, you can contact us directly.

Example of the OOP with Python

Before going into the details of the OOP, now is the time to discuss why we are emphasizing the importance of the OOP and how we explain it with Python. The whole concept will be clear with the help of the following example:

Think of a dog that will be taken as an example by a class. Here, we have taken a general example that is common in the real world. Think of all the characteristics of the dog that may be either physical or natural habits of the dog. The general class of dog may have many types, such as the breed of the dog. There are hundreds of breeds of dogs, and these are considered the basic members of the class "dog." 

Moreover, different dogs have different kinds of attributes such as their size, colour, skin type, age, and other characteristics that are said to be their instance attributes. On the basis of these attribute, the division of the dogs is done into different classes. 

Moreover, the way the dogs bark, their favourite food, and their daily routine make them more specific, and these are referred to as the methods of that particular class.

Importance of Classes in Python OOP

The class is the basic unit, without which, the programmers may not think about the OOP in any way.  This is the prototype with which the whole OOP process is carried out. You can think of a class as the blueprint of the house (let's say). In this way, the information about the floor, walls, rooms, windows, doors, etc. In this way, the whole house is made by following this blueprint(class) whereas, the result, that is the house is the object. Let us prove all this information with the help of this example.

Syntax of the Class

The class is simply made in Python with the keyword “class” and the name that we want for our class:

class myClass:

    # class definition

Here,

class=keyword

myClass= the name of the class given by the programmer.

In this way, with the help of simple lines, the creation process of the class is carried out. Now, the definition of the class is in the new line. To make a clear difference, a colon is used after the name of the class. You must keep in mind, the class name is a single word, no matter what the length of the name, and there must be no space between the name of the class. 

Example of Class in Python

In the example of the class given above, where we were talking about dogs. We are using the same example and will show you the result by using them in the example. To start with a simple example, the class with only three attributes. 

Code for Class

#declaring the class

class myDog:

#defining attributes

    def __init__(self, name, age):  

#using the attributes and storing them in the new names

        self.name = name

        self.age = age

#usign the stored name to print the results

tinku = myDog("Tinku", 2)

print("The name of the dog= ",tinku.name)

print("The age of the dog= ",tinku.age)

Output:

Let's see what happens during this code:

  • First of all, we created a class with the class keyword, and this time, we named it “myDog” so you are providing the information about your dog( if you do not have it, just imagine it) and we are writing the particular features of that dog. So, the class is myDog, and all the other features are its attributes. 

  • In the next step, we are defining the characteristics with which we want to describe our dog. Here, name and age are the attributes. That is taken as one of the two arguments we are defining to use later.

  • The "self" keyword will tell us that name and age are the special attributes that we want to use here.

  • In the end, a new unit is formed, where this time, we are using the values of attributes instead of the names. The first step was only to give the base of what we wanted, and this time, we will assign values to these attributes. 

  • You can see, the name is in the form of a string, therefore we have used a double quotation. In this way, we do not have to specify the data type but just represent it in a specific way. 

  • In the end, it's time to print the result and to make the message clearer, we used the written message and then declared the value we wanted.

We can add more and more attributes to make the class clearer and store data about the dog, such as its colour, fur type, etc. This is a simple example to show you how the class works. 

Objects in Python OOP 

The workings of the class are not just limited to one product. This is the good thing about the OOP is, it provides us with the versatility to work in a different way with the same code. In the example given above, if more than one breed of dog is to be stored, then we will make the objects of the class "dog."

Code:

To understand the objects in interesting ways, we are moving towards real-time applications where different objects are made and then used in a specific way. Let us take an example where we have different types of dogs with different ages, and the combination of the ages of the first two dogs is the age of the third dog. So here is the question that can be asked of you in the examination. 

Question:

Write the code to get the age of a dog that is the combination of two dogs and get the input from the user for it. 

Answer:

#declaring the class

class myDog:

#defining attributes

    def __init__(self, name, age):  

#using the attributes and storing them in the new names

       self.name = name

       self.age = age

#using attributes in string message

    def dogInfo(self):

            print(self.name + " is " + str(self.age) + " year(s) old.")

#printing queries and getting input from user            

print("What is the age of happy")

AgeOfHappy=input()

print("What is the age of sunny")

AgeOfSunny=input()

AgeOfFancy=int(AgeOfHappy)+int(AgeOfSunny)

#using the inputs to guess the age of fancy 

print("Age of fancy= ",AgeOfFancy)

#printing results

happy = myDog("Happy", AgeOfHappy)

sunny = myDog("Sunny", AgeOfSunny)

fancy = myDog("Fancy", AgeOfFancy)

happy.dogInfo()

sunny.dogInfo()

fancy.dogInfo()

Output:


Discussion:

This program has many interesting features, and these will become clear with the help of this discussion. 

  • At the beginning of the program, the class “myDog” is created so that we may give the same attributes to different objects. 

  • To declare the attributes we are using here the “def” keywords to define the keyword then the 

  • Attributes are mentioned so that we may use them later.

  • The next step is to define the message, in which we will use the attributes and get the result in the form of a message. Here, the point to notice is, we are using the string keyword for the "age,” but how can age be a string? Actually, we are using it in the string message, and if we declare the “int” here, the compiler, when it reaches this point at the output, will throw the error and not print the whole string. 

  • After that, the whole mechanism is used in which we are printing the message to input the age of the first two dogs and get the output in the form of integers. 

  • Here, if the user inputs a data type other than an integer, it will also result in an error. 

  • Both these ages are then added, and the result is saved in the “AgeOfFancy” variable.

  • The object we have just used to print the results.

So with the help of this discussion, we come to know that the object consists of the following features:

Attributes of Objects:

Each object has its own set of attributes, which are variables that store information about the object's current state. We can say that objects are made of attributes. Yet, there are different types of attributes in OOP, and the following are some of the most important characteristics of attributes:

  • Instance variables: These are defined within the class but are unique to every instance of the class.

  • Class variables: These are also defined within the class but are shared with all the instances.

  • Methods: These are used to manipulate the object’s state and are defined within the class to operate the attributes. 

  • Special methods: These are also referred to as the magic methods and these tell the compiler how objects will behave under certain conditions. These are denoted by the double score in the name as we have just used in the previous code of dogs. 

  • Inherited attributes: These are used to reuse the modularity in the code as these are inherited by a subclass or a superclass. So it makes working easy.

The Behaviour of Objects in OOP

When an object is created in OOP, it has its own set of behaviours, which are defined by the methods in its class. These methods can be used to change the state of an object. Another function of the behaviour is to carry out other operations related to the object's behaviour. For example, if we declare the object of a car, we might have methods such as:

  • start engine()

  • accelerate()

  • brake()

  • turn()

These methods define the behavior of the car object and enable it to perform the actions that are expected of a car. These are just simple examples, and we can add more and more behaviors, just as a car can do hundreds of tasks.

Hence, in this lecture, we read a lot about objects and classes. There are different entities that are used in OOP, and objects and classes are the basics. We must know that objects and classes are used simultaneously, and for a better understanding, we learned the classes first and then examined where and how objects are being used. Moreover, different types of objects and fundamental knowledge about their pillars are discussed here. We have a lot of information to share with you, and you must have noticed that Python is now more complex but useful when we use the concepts of OOP. We have some mini Python projects to share with you in this tutorial, so stay with us for more programs.

Object Oriented Programming in Python

Hey peeps! Are you excited to begin with the new chapter in Python? Till now, we have been learning the data types and their related concepts. Now, we are starting a new chapter where you will learn the details of Object Oriented Programming or OOP. We are moving towards the advanced level of programming in Python, and here, you will go through the complex but interesting concepts that will show us the fascinating results on the screen. This will be more clear when you will know the basic information about the OOP, but before going deep, we will go through the headlines of the lecture:

  • How do you classify the programming languages?

  • How do you introduce the OOP?

  • Why object-oriented programming is important in Python?

  • How do you define class and objects in OOP and how are they connected?

  • What are polymorphism and encapsulation?

  • How do you use the inheritance in OOP?

  • How do you understand data abstraction in OOP?

  • What does method overloading mean?

Keep in mind, it is not a specific concept with Python but any higher-level programming language that supports the OOP has the same concepts and we are using a very general way to describe all the concepts.

What does Type of Programming Language Mean?

Before going into the detail of this topic, it is helpful to understand why we are emphasizing on the OOP and its importance. Actually, there are different types of programming languages and being a programmer, you must know the basic categories. Some of the important types of programming languages are:

  • Procedural Programming Language

  • Functional Programming Language

  • Object-oriented Programming Language

  • Scripting Programming Language

  • Logic Programming Language


Out of which, we are interested in the OOP. The reason why the type of programming language is important, it describes the paradigm of the language, and therefore, we can understand the nature and the importance of that particular language in the profession you are using it for. Here, we should know what exactly the “paradigm” means:

“A programming paradigm is the concept to which a programming language's methodology adheres."

 Paradigms are significant because they define a programming language and its operation. The classification of the programming languages is done by keeping its paradigm in mind and in this way, the programmer may choose the type of programming language that exactly suits the application for which the coding is required.

You can see that OOP comes in the imperative paradigm. In imperative programming, the user typically interacts directly with the computer's state, deciding how things should be calculated. In this way, more control is in the programmer’s hands, which is the basic source of attraction towards this programming language. In the practice of programming, I am sure you have touched other types of languages as well at any point. So, it becomes easy to compare and practice the code.

What is OOP in Python?

In real-time education, different types of subjects are taught to us by teachers. We are moving from basic to advanced programming in this course; therefore, we have covered the concept of data types before. This time, the OOP is our source of attraction, and we are going to learn it deeply because the programmers, most of the time, deal with the OOP when they are using the practical applications of the programming. Let us look at the introduction to the OOP:

“OOP (Object-Oriented programming) is a programming paradigm that organizes and structures code using objects and classes.”

For now, do not bother about the special terms used in this definition. We will learn a lot about them in these lectures with the help of different terminologies. Hence, if anything is causing confusion, do not worry because everything will be clear in just a bit. 

The concept of OOP is so vast and important that it is widely used to write powerful applications. The data engineers have to write these applications to access and use the data stored in different entities. 

The feature that makes the OOP unique is, it uses concepts that not only make the programming easy but efficient. It is based on the imperative programming paradigm, which employs statements to alter the state of a program. It is concerned with describing how a program should work. One must keep in mind that the main objective of the OOP is to bind the data and the functions of the program in such a way that all of these may work as a single unit but the security of the data remains intact. There are some important terms that you will see often in these lectures, so have a look at all of them.

  • Class

  • Objects

  • Polymorphism

  • Encapsulation

  • Inheritance

  • Data Abstraction

Keep in mind that you have to grasp the concept of each of these terms clearly so that, when you read them with other types of definitions, you may not be confused. You will learn all of these in detail in the coming lectures, but the basic introduction to all of them is given next:

Class in OOP

Before going into the introduction of the OOP, one must know that an object is an instance of a class. Object and class are interconnected terms, and a class is defined as:

“In OOP, a class is a basic unit that represents the collection of objects, and it can be thought of as the blueprint or the prototype by following which, the objects are made.”

The attributes of a particular thing, connected with each other, can be represented with the help of the class, where the number of the attributes starts at one and can be two, ten, or any other positive number. In this way, a simple and basic class can be used to store all types of physical or logical information about a particular product. 

Objects in OOP

In object-oriented programming, objects are the basic units of data. An object is associated with the class and is the entity with which the state and behaviour of the class are associated. If it is confusing at this point, do not worry because we are going to discuss the object in detail and will work again and again with the objects.

The good thing about the objects in OOP is that, just like the real-time concept of objects, the programming objects may be anything, whether it is physical, such as a car, an animal, a plant, a cooking item, any food, or any other thing, or abstract, such as any software, a bank account, a soft blueprint, or any document. The positive thing about the object is, it allows us to reuse the same code anywhere in any block of the same code where the same attribute of the object is to be used.

Polymorphism in OOP

The fundamental concept of the OOP is polymorphism, and it has the same features as the family in real life. To keep things simple, we assume that all the objects belong to the same class, and the polymorphism allows us to use the objects together as they are from the same family. In this way, the same objects can be used interchangeably in the same context. In this way, the workload of the programmer is minimized as much as possible through polymorphism. In simple words, the concept of polymorphism is the same as it is in chemistry, where the same element can be used in different ways when certain conditions are met.

Another feature that makes the polymorphism attractive is the availability of the alteration in the classes, both in terms of their size and the data stored in them. All this information will be cleared up in the coming lectures, but for now, we only understand the basics of polymorphism. In other words, we all know that poly means "many,” and if we talk about OOP, it includes the concept of a class's ability to get the features of already existing classes in this way. For example, you can assign the attributes of a particular product, such as a car, to another car with the same basic features but with different attributes. This is just a basic example of polymorphism, and many people mix this concept with inheritance, but these are different, and you will learn a lot about them in the next lectures.

Encapsulation in OOP

The next concept that we are going to discuss is encapsulation, and to make your concept clear, let us take the example of the capsules that we get from the pharmacy for different health issues. These capsules protect the inner medicine, and the same concept can be applied to this type of encapsulation to reinforce the concept. Basically, the data is protected with the help of different concepts used in the encapsulation.

The programmers are very sensitive about their codes and the data stored with the help of these codes. Encapsulation is used to give the code privacy and protect it from unwanted users. The private attributes of the code that are enclosed in the capsule are only accessible by the programmer itself. In other words, we cannot use the private attribute in other blocks of code until the programmer himself allows it. 

Inheritance in OOP

Another important feature of the OOP is inheritance, and this is the point where we can say that the OOP is making Python more effective and easier to use. It is one of the most significant points of the OOP, and with the help of easy and effective Python, programmers can inherit the characteristics and attributes of any class and assign them directly to others. For this, you have to learn about the child and parent classes, but for now, we are leaving this topic here and moving on to the next point that will show us the importance of the OOP, especially when we use it in Python. 

Data Abstraction in OOP

If you are interested in becoming a professional programmer, then some points should always be kept in mind, and the most important one is to always go with clean code that precisely describes the code and gives the exact coding without any errors. For this, some concepts will help you a lot, and one of them is the concept of data abstraction. With the help of this concept, the programmer is able to code cleaner because "data abstraction" means writing cleaner code and hiding unnecessary details from the users. It is yet another method for the programmer to maintain privacy from the end user. THE SENSITIVE CODES ARE HIDDEN FROM THE OTHER USERS USING DIFFERENT TECHNIQUES. The whole process of data abstraction revolved around making and implementing the abstraction classes and then calling them in different ways according to the requirements of the code.

Method Overloading in Python

Here is a small topic to be discussed that is not a particular part of OOP in Python, but almost every programming language that works with OOP has it. This is also true for other characteristics that we have discussed so far. 

In method overloading, many methods with the same name are declared and then called at once. In this way, a single class can take multiple arguments. Other concepts, such as method overriding, are also connected with the same concept, and we will discuss them with some suitable examples. 

Consequently, we have almost all the basics of the OOP. We have read a lot about them and tried to make them more general so that the programmers working on them other than Python may also get the useful concepts from this lecture. Actually, the OOP is not just confined to Python, but we have to connect it with Python, and this will be more fully discussed in the next lectures, where all these concepts will not only be discussed but the practical implementation of codes will help us to have a grip on Python. This is an extremely useful topic and therefore, we will move a little bit slowly on these lectures and will understand each and every point in detail. 

For Loop with Examples in Python

Hey peeps! Welcome to the new tutorial for the Python programming language, where we are at the point where we are going to learn about the loops. Loops are fundamental concepts in programming, and if we talk about Python, there is a smaller variety of loops in it, but the most important ones are available to practice in Python. In the last session, there was a long discussion about the while loop in detail. We had seen some examples and the details of the statements that can be used within the while loop. In the present lecture, we are going to discuss the second type of loop in Python, that is, the for loop. You will go through the training of every important and basic step about this loop, but first of all, you have to look at the basic list:

  • Why do we prefer for loop over some other concepts in Python programming language?

  • What are some basic concepts that every programmer must know about the for loop in Python?

  • Describe the flow chart of the for loop.

  • What are some examples that explain the for loop in Python?

  • How do we use different sequences in the for loop?

  • What is the range function explain it in detail by using the for loop in Python?

There are other ways to get the same output as we will get in this lecture but using the for loop is one of the easiest and most fundamental ways to get the best results. Have a look at the detail of each question. 

What are The Advantages of For Loop?

The for loop is the basic looping process in Python that is extremely useful in making the basic to higher level codes in simpler way. We all had the introduction of the For loop in the previous lesson, and now, have a look at the following positive points about this loop:


Simplicity in Code Using For Loop

The for loop makes the code very simple and the programmers do not have to pay much attention to make the logic. You can get the idea of its simplicity that the user can initiate the loop in just a single line if all the logic is clear in it. After that, the body of the loop starts. Just like other loops, the For loop gives us the independence to adjust the flow of the code so that we do not have to write the same block of the code again and again.

Implementation of For Loop on Data Types

Different data types can be used in the for loop and the best thing about it is, it becomes super easy to use the For loop to manage the sequences. It would not be wrong to say that For loop makes the working of the sequence best therefore, for loop is perfect for the sequences such as lists, tuples, and arrays. Moreover, the traversing of the sequences is easy with the For loop. 

General Loop

The for loop is not a new concept but in the old higher-level programming languages such as C and C++, for loop is used therefore if a programmer is moving from such basic programming languages to Python, the concept will be cleared before they start it. In other words, the for loop is a generic type of loop that once understood, can be useful as well when they switch to the new programming language. 

Basics of For Loop

We know the introduction of the for loop but this time, we are going to discuss the detail of every process that will be useful in the practical coding using the for loop. Keep in mind, loops are the statements and not the whole code. This helps to manage the code in a better way and to reuse the same block by merely inserting it in the body of the loop. 

Syntax of For Loop

We are discussing the generalized form of the For loop and therefore, all the concepts are very general that we have discussed till now. Yet, the only difference in the coding is the syntax of the loops and therefore, we are discussing it at first to get an idea of what actually is going on.

for iterator in sequence:

   statement(s)


It seems very simple here but the statement is not that much simple. The programmers, then using the for loop add multiple statements in different ways to get the required output. More things will be cleared when you will see the flow chart. 

Flow Chart of The For Loop

The best way to get the concept of the for loop is to check for the flow chart of this loop. Have a look at the picture given next and then we will move towards its discussion.

Here, you can compare the syntax and flow chart and get an idea of what happens when data is input in the for loop. At the start, when the condition is applied on the for loop, the compiler checks for the condition if it is true or not and as you can guess, if the condition is true, the compiler will check for the body code 

Examples of Data Types with For Loop 

Different data types can be used with the for loop and we will move from basic to complex ones. We all know about the string; therefore, here is the first example with the string message.

String with For Loop 

#initializing the message

message= print("Enter the string")

#taking input from the user

str=input(message)

#using for loop to print the message from the user

for i in str:

  print(i)

Output

Here, when we run the program, we get the dialogue box it says the “none” word with the dialogue box. This will look strange but it makes sense. With some functions in Python, the return value is mentioned in the output. Since this function will not return any result but will only give us the same string that we are going to input in it, therefore, there is the word “none” mentioned in the dialogue box. We can solve it in different ways but the point I want to make here is to clarify the reason behind this indication.

When the string message is typed by the user, the same message with the same format is shown on the screen but this time, as we are using the for loop, each character is picked by the compiler one after the other and therefore, the result will be obtained in the vertical form with each character at the new line. 

Here, you can see the “none” is added by default without a string message and once it is printed, the for loop picked each character and printed it in a separate line. Even the spaces between the words are counted, and we get a clean and understandable output. 

Have you tried the code given above? If yes then there must be a question in your mind that what happens if we input any other data type instead of string? Actually, this is not a precise code yet, if we add the restriction to add only the string as we have done in the previous lecture, the compiler will not accept any other data type other than string. Yet, to keep things simple, I am not changing the code as the main focus is on the for loop till now.

Sequences in Python Using For Loop

Here comes the practice that is specialized in the for loop. Since the beginning, you have been noticing that we are emphasising the sequences. We all have practised them and in some examples, the for loop was used before but since this is a pure practice of the for loop, I have made a program that contains all important sequences in a single program.

Code of Sequences:

#initializing the List to use with the For loop

print("\b Names of the fruits")

fruits= ["strawberry", "cherry", "blueberry", "apricot", "tomato"]

for i in fruits:

  print(i)

#initializing the tuple to use with the For loop

print("\b Price list of mentioned fruits")

priceOfFruits= (34.8, 11.7, 126.9,11.6,11.5,22.0,1)

for i in priceOfFruits:

  print(i)

#initializing the array to use with the For loop

print("\b Random things and numbers")

items= {"lipstick",3,"papers", 3, "pen", 1, "bread", 3.4 }

for i in items:

  print(i)

Output:

Hence, the program is clear as we have practised it before. The type of bracket represents each sequence and it has its own characteristics. For loop access each and every element of the sequence and print it on the screen. The arrangement of the items in the array is random and we can not suggest the sequence of the elements because it randomly picks the elements and print them. Hence, every time we run the code, the value stored in the variable i is different and the one, printed on the screen, is never repeated at that particular run time. 

Range Function in For Loop

The next topic here is the range function that has interesting applications in the fields like gaming. It is because it can be used in different ways as it has the independence of the number of parameters. The syntax of the range function is the same with the for loop as it is with other statements.

x=range(start, stop, step)

Where,

x=name of the variable in which the value of the range is being stored.

start=starting point of the series 

stop=ending point of the series

step=The interval between the range member.

Keep in mind, you can use one, two, or three parameters at the same time according to your easiness. Instead of using separate examples for each case, we have designed a program that describes the all. Have a look at the code and then we will discuss it more. 

Code of Range Function

#using the range function to print the table

num = int(input("Enter the integer for which the table is required? "))

for i in range(1,21):

   print(num,'x',i,'=',num*i)

#range function with one parameter

print("\b using the range function with only ending point")

for i in range(7):

    print(i)

#range function with two parameters

print("\b using the range function with starting and ending points")

for i in range(2,9):

    print(i)

#range function with three parameters

print("\b using the range function with start,end, and step points")

for i in range(1,10,3):

print(i)

Output

Discussion about The Range Function

For your convenience, we will go through the basic to the complex concepts.

  • The three parameters are useful to get a uniform series of numbers.

  • Only integers can be used with the range function.

  • If the start point is not mentioned, it always starts from zero.

  • The stop parameter is the compulsory one to use in the range function.

  • To make the restriction of only integers, the “int” keyword is used with the input function in a specific syntax.

  • You can get the table of any number with the range of any integer easily using the range function.

  • For loop is the best way to get the required output from the range function. 

Consequently, we can say that we are not beginners and instead of learning the long theories about the basic concept, the focus of our lecture was towards the practical examples of the for loop therefore we started this lecture with the introduction and then moved towards the basics, syntax, examples, and the codes using different data types. As the specialized data type of the for loop is sequence, therefore, we had the practice of the for loop with the sequences. Using the range function with for loop gave us the interesting outputs and with the help of these examples, we learned the for loop in a better way. The upcoming lectures are interesting tooo so keep practicing and stay with us.

Multi-Dimensional Arrays in Python

Hello learners! Welcome to the next episode of the arrays, in which we are moving towards the details of the arrays at an advanced level. In the previous lecture, we covered the introductions and fundamentals of arrays, dimensional arrays, and array operations. One must know that the working of the arrays does not end with simple operations, and there is a lot to learn about them. Arrays and their types are important topics in programming, and if we talk about Python, the working and concepts of the array in Python are relatively simple and more effective. The details of the advanced types of arrays will prove this statement. We have a lot of data to share with you, and for this reason, we have arranged this lecture. It is important to understand the reasons behind the reading of this lecture.

  • What are two-dimensional arrays, and how can we perform them in a Jupyter notebook?

  • How can we access all the elements of the two-dimensional arrays?

  • Can we insert the elements in the two-dimensional arrays?

  • How do we update our 2D array?

  • Is the appending process easy in the 2D arrays in Python?

  • Explain three-dimensional arrays and provide an example of how the array is updated.

All of these are important interview questions, and you will learn the concept through its practical implementation, so stay with us till the end of this lecture to get all the answers.

Two-Dimensional Array in Python

We all know a lot about one-dimensional arrays and have seen these concepts at different levels. In this type, we are dealing with the arrays at an advanced level, and to understand them, we will work on the Jupyter notebook. The second type of array is a little bit different, and we can say it is twice as difficult as the one discussed before. We all know the concept of dimensions from physics classes, and these concepts are also true for arrays. These are also referred to as "multi-dimensional arrays," and we define them as:

“The 2-D arrays are the type of arrays that are shown by two indices, and these contain rows and columns to save the data in the form of matrices.”

As you can guess, these are comparatively more complex than the one-dimensional arrays, and storing the data in them is more useful and has many applications in real life. While performing the example of a 2D array, we are going to use the simpler way where the user just has to mention the numbers of rows and columns and an array is ready. 

Syntax of a 2D Array in Python

array-name = [ [d1, d2, .... ,dn], [e1, e2, .... ,en] ]

Here,

d1,d2,...,dn=number of elements in the first dimension

e1,e2,...,en=number of elements in the second dimension

The numbers of the elements vary from zero to infinity. For more detail, have a look at the example given next:

#Initializing the two-dimensional array

array_input = [ [10.9,78.9,111.90] ,[8.0,771.2,2.0] ]

#showing the elements of each dimension separately

print("The elements in the first dimension = " ,array_input[0])

print("The elements in the first dimension = " ,array_input[1])

So you can see that the initializing of the array with the floating elements is done in the first step. Here, the point to notice is the usage of square brackets, and you have to remember that no other type of array is used in this case. 

Accessing the All Elements of Array

In the previous case, you have seen that if we wanted two or more elements as output, there was a need for more than one print function. Yet, there are also cases where the whole elements of an array are required on the screen. For this, the programmers use different types of iterations according to the requirements and get the results. We have seen the working of the iterations many times in this course and therefore, there is no need to explain why we use it. Arrays are one of the best examples to check the working of the iterations. In all the examples of the arrays, you will see the use of for loop in the nested form because we are dealing with  two-dimensional arrays.

Inserting New Elements in 2D Arrays

One must be wondering how we can add more elements to the two-dimensional arrays because of the matrix-type arrangement of the lament. For this, the method is simple, and by discussing it, we will learn the “input” method of Python. Have a look at the code given next, and we will discuss the details in just a bit. 

#importing the array from the Python 

import array as twoDArray 

#declaring our array with two dimensions of the order 2 by 2

twoDArray = [[2,2,2,2,2,2,2], [6,6]]

print("Array before insertion of elements: ", twoDArray)

#Inserting the elements in the matrix at position three

twoDArray.insert(3, [4,7,4,2,9])

print("Array after insertion of elements: ")

#Using nested for loop to inset the elements one after the other at the required position

for x in twoDArray:

    for y in x:

        print(y,end = " ")

    print()

The following points are to be discussed according to this concept:

  • Importing the array makes the code easy and effective.

  • The two-dimensional array is nothing but the arrangement of elements in the form of rows and columns. 

  • The number of rows and columns is not restricted to each other, that is, there is no restriction on using the square array all the time, and the number of elements in rows and columns may be different from each other.

  • The square brackets are used in the two-dimensional arrays in every case, whether it is the outermost bracket or dimensional bracket. 

  • Special functions such as insert, delete, etc. can be used by using the dot operator with the name of the array. 

  • To insert the elements in the two-dimensional array, a nested for loop is efficient where two loops are being used. The syntax is important in this case. 

Other rules of the code are discussed in different lectures in this course. 

Updating of the Elements in an Array

The next case that we are going to discuss is the updating of the elements in the arrays. Think about the situation when you first declare the array and work with it, but after some time, you have to change some of the elements of the arrays. In such cases, the insertion and deletion operations that must be done are time-consuming. The best way to do this is to update the elements directly. The reason why I mention this detail is that arrays are unchangeable data types in other programming languages such as C++, and once declared, the arrays can not be altered in such languages. Yet, Python gives us the ease to update, delete, insert, and change the arrays in the programs. We know programming is a vast procedure and there are several ways to do the same task, but for you, we have picked the simplest and most interesting way to do so that is given in the code next:

#Importing the array

import array as Updation

#Declaring a two-dimensional array

Updation = [[22,56,4,1], [2,4,6,8,10]]

print("Array before Updation of elements: ", Updation)

 #updating the elements in the second array and the third element of the first array

Updation[1] = [44,89,2,0]

Updation[0][3] = 5

print("Array after update of elements: ")

#using nested for loop to print the array

for x in Updation:

    for y in x:

        print(y,end = " ")

We are now able to understand such codes; therefore, there is no need for long descriptions. But, the point here to notice is, in the same code, merely by declaring the elements at certain positions, the array can be updated and the previous values are then ignored. 

Appending the values in the Array

In the previous lecture, the element at the end of the one-dimensional array was appended easily. Yet, you must think that more detail is required for the appending of the data because it has to be mentioned where the exact place is where you want to append the data. So, if you remember the previous lecture then you will find it different to append this type of array.

#importing the array 

import array as myArray

#initializing our array

myArray = [[1.4,66.90,234.0], [009.6,127.8,34.0,11.34], [0,2]]

print("Elements of my array = ", myArray)

#Using the length operator to check the length before appending the elements

length=len(myArray)

print("Length of the array before appending: ", length)

#The process of appending

myArray.append([7.9,334.90,2303])

#calculating and printing the length after appending elements

length=len(myArray)

print("Length of the array after appending: ", length)

#printing  the results after appending

for x in myArray:

    for y in x:

        print(y,end = " ")

    print()

The difference is clear; the number of elements can be easily compared with the help of the length function. We have used the length function many times in this course, and here you can see a better example of how to use it.

Three Dimensional Array

The three-dimensional array is the most complex form of the array discussed so far, and usually, at this level, the learner does not go into the details of the three-dimensional arrays to avoid complexity. The 2D array has many interesting applications and has the ability to store a lot of data in a cleaner way; therefore, 3D arrays are not used much for learning purposes, but if we talk about complex applications such as gaming and other fields, the 3D arrays have a great scope. 

The form of the 3D array can be understood by keeping the matrix of the order 3x3 in mind. Here is a little information about the initialization of the three-dimensional arrays in the Jupyter notebook. 

#initializing my three-dimensional array

ThreeD=[[[22.5,[67.9],[44.4]],[5],[23.8]],[[12,[123],[893]],[0],[78],[126]],[[70],[11]]]

print("The three dimensional array =  ", ThreeD)

#Simply updates the elements by mentioning the locations and values.

ThreeD[0][0][0] =11

ThreeD[1][0][0]  =21

ThreeD[0][0][1] =111

#Printing the results 

print("After updating the elements the array = " ,ThreeD)

Hence, this picture gives us information about the shape and form of the three-dimensional arrays. Do not think that 3D arrays have the form of a 3-by-3 matrix. I suggest you take a deep look at the brackets of the array that we have mentioned here. The complexity of the three-dimensional array is much greater than in previous cases. To make it simple, we have used the single element in the single brackets, but there are more options for the same work that will be unnecessary to learn right now. 

Another thing to be mentioned here is that, for simple operations such as displaying and updating the elements, there is no need to import the array every time. Yet, we have used it to display the proper professional coding of the array. We are not talking about the three-dimensional arrays in more detail because they are very difficult to understand and because there are some other options that work better than the three-dimensional arrays. You will learn it in detail in the next lectures. 

Therefore, we can say that we have learned a lot about the advanced level of arrays in Python which are two-dimensional arrays and three-dimensional arrays. It is interesting to note that dealing with arrays is much easier in Python than in any other programming language. Therefore, we always say that Python is interesting and easy to learn. The topic ends here, but the detail of data type is not limited to just the types of array. You have to learn a lot about iit,and we are here to share every single and necessary detail in a simple way. So, stay with us in this learning phase.

Python Arrays Practice in Jupyter Notebook

Hello Python programmers! Welcome to the engineering projects where you will find the best learning data in a precise way. We are dealing with Python nowadays, and today, the topic of discussion is the arrays in the language. We have seen different data types in Python and discussed a lot about them in detail till now. In the previous lecture, we saw the details of the procedures in dictionaries. There are certain ways to store the data in the different types of sequences, and we have highlighted a lot about almost all of them. It is time to discuss the arrays, but before this, it is better to understand the objectives of this lecture:

  • Introduction to arrays

  • Difference between contiguous and non-contiguous memory locations

  • One-dimensional arrays

  • Functions in arrays

What are Arrays in Programming Languages?

If you are from a programming background, then you have surely heard the name "arrays" and used them in your practice. Yet, if you are a beginner, you must know that arrays are present in almost all types of high-level programming languages. The array is also the way to organize and store the data in a sequential way, but it has some very basic characteristics, most of which are similar to those of other data types, but some are a little bit different, and we will work on both of these types. But before that, let's take a look at the basic definitions of an array:

“An array is a collection of items that are stored in contiguous memory locations. The idea is to group together items of the same type.”

This makes calculating the position of each element easier by simply adding an offset to a base value, i.e., the memory location of the array's first element. These are used to store a gigantic amount of data in different departments and offices, and because it is an old technique, people prefer it to other types such as sets, lists, and dictionaries.

Contiguous Locations in Array

When working with arrays, you will always notice the term "contiguous," and it makes sense because it is the best word to describe the structure of the array. It is the finite collection of data in which the elements are arranged strictly one after the other in the successive locations of memory, and in this way, a contiguous structure is obtained just like a ladder in a horizontal way. If you think it is all about knowing about the contiguous memory locations, then you are wrong. But, it is better to understand the concept by comparing it with the help of the opposite of it, that is the non-contiguous memory places.

Sr #

Feature

Contiguous Memory Allocation 

Non-Contiguous Memory Allocation 

1

Definition

Contiguous memory locations are the type of allocation that allocates a continuous block of memory without skipping any places. 

Non-contiguous memory allocation, on the other hand, is the type in which memory is not continuous but separate blocks of memory are allocated regardless of how little space exists between them. 

2

Complexity

The control of the operating system is easy in it because the memory can be smoothly be accessed. 

In this case, controlling the OS is comparatively difficult.

3

Execution time

The execution time is faster as compared to the other type, and it makes sense because the compiler does not have to sense the gap and then jump according to the length of the gap. 

In this case, the execution time is longer than in the first case because the compiler jumps from one memory location to the other. The time is determined by the gaps between the allocated memory.

4

Overhead

Because there are fewer address translations when dealing with contiguous memory allocation, there is less overhead.

Because the address translation is greater in this case, we have more overhead.

5

Special Features

The contiguous memory allocation contains single-partition allocation as well as multi-partition allocation.

When dealing with non-contiguous memory allocation, paging and segmentation are observed.

6

Type of Fragmentation

These include both internal and external fragmentation in the case of contiguous memory allocation.

The internal fragmentation does not occur in this case, and we get only external fragmentation.

7

Swap-in process

It is noted that the swap-in process can only be arranged in the space that was originally allocated.

If we talk about the non-contiguous memory allocation, the swap-in process is arranged in any memory allocation, so we get versatility in this case.

8

Wastage of memory

In this case, the wasted memory varies according to the array we are using. 

It is an advantage of this type of allocation that no memory is wasted in this case.

9

Types 

There are only two types of contiguous memory allocation:


  1. Fixed(or static) partitioning

  2. Dynamic partitioning


The hint for this point is also given in another feature.

We observe five types in this case that are mentioned below:

  1. Paging

  2. Multilevel Paging

  3. Inverted Paging

  4. Segmentation

  5. Segmented Paging


All of this is unnecessary in our case; thus, do not go into detail about this type of situation.

Importing the Array in Python

This is the distinguishing feature of arrays in Python when compared to other programming languages. Arrays, like many other functions and data types, are pre-defined in Python for the convenience of programmers. Because arrays are very general data types that programmers frequently use, it is simple to declare and import arrays in the same line and then begin working with the arrays. There are several ways to use arrays in Python, one of which is to import the arrays. Have a look at the details of this process:

There are different steps that are to be followed when dealing with the arrays in Python, and these are mentioned here:

  1. Import the arrays.

  2. Declare the name. 

  3. Use the array in different operations. 

Hence using these steps, the arrays are used in different ways and it is interesting to notice that the declaration and the usage of an array are very different in Python as compared to other higher-level programming languages such as C++, C#, etc.

To understand well, let us see all these steps in action, but I want to discuss the type of the arrays with you while performing all these steps so that we may understand both these concepts one after the other.

Dimensions in the Arrays 

Here is the point of the array that makes it different from the dictionaries and sets we have mentioned before. The arrays can be made in three ways:

  • One-dimensional array

  • Two-dimensional array

  • Three-dimensional array

Now it's the choice of the programmer according to the requirement, which type of array is he or she using. The details of each of them will be shared with you in just a bit, but before that, open your Jupyter notebook so that we can apply these arrays practically side by side.

  • Go to the search area of the window and get the Jupyter notebook there.

  • A screen will appear in front of you, and you have to go to the drop-down menu that is present on the right side of the screen.

  • Choose python there and wait for the new tab to open on your browser. 

  • Click on the new cell location and start coding. 

One-Dimensional Array

The most basic and commonly used array is one, and it does not require much effort for you to understand its concept. The very basic structure of the array that we see in the examples and discussion The elements are arranged one after the other, and the index starts at the first place where the zero number is assigned to that location. All the elements are linearly arranged, and it is the simplest form of array that is easy to create and access. In this way, the programmer gets the collection of the same data type in a linear format. The array is then stored in a variable to be used in different ways.

#importing the arrays from the Python library

import array as myArray

result = myArray.array('i', [22,68,123,90,49,167,66,129])

# accessing elements of array and printing it

print("Accessing the first element ", result[0])


print("Accessing the fourth element ", result[3])

The following output is observed as a result:

Hence, the single elements can be accessed in this way. Have you noticed that in the array, we have mentioned the “i” before, and after that, a list is being used? It has a very special reason, and you can check this by deleting the “i” in the code. You will observe that the compiler is throwing an error about the declaration of the Unicode character. Always remember that if the programmer is using the import array method in Python, there is a rule in Python for using arrays that the first argument of the array is always a Unicode character.

Functions for the Arrays in Python

Here comes the reason why we are importing the arrays into Python. The primary reason is, it has multiple functions that make the work super easy, and the programmers do not have to write the codes again and again. I am just sharing the very basic and common functions. So let’s jump to the codes:

count() in Python using Array

Take the example in your mind that when you are dealing with a gigantic amount of data at the same array and it becomes tedious to search for the frequency of the particular item. In such cases, when the detail of the element appearing in the array is required, the count function is used. The working of this function can be understood with this example:

#Declaring our array of strings

import array as myArray

result = myArray.array('i', [22,68,123,90,49,34,67,22,90,33,7,11,8,44,11,77,23,90,28,541,490,299,611,20,561,112,3,88,167,66,129])

#Using the count function to get frequency

print(result.count(90))

So, when we check the frequency of the number 90, we get the following output:

Hence, we can easily conclude that in our array, the integer 90 appears three times. 

append() in Python Array

The next function that is to be tested is the append function. For this, we add a new element at the end of the array, and doing this is very simple, as you can see in the code given next:

#Declaring our array of integers

import array as myArray

result = myArray.array('i', [22,68,123,90,49,34,67,22,90,33,7,11,8,44,

                             11,77,23,90,28,541,490,299,611,20,561,112,3,88,167,66,129])

#appending a new 90 at the end of array

result.append(90)

print(result)

reverse() in Python Array

The next function is reverse(), and as you can guess, the reverse of the array can be obtained with the help of a short command that we are going to test in the code next:

#Declaring our array of strings

import array as myArray

result = myArray.array('i', [22,68,123,90,49,34,67,22,90,33,7,11,8,44,

                             11,77,23,90,28,541,490,299,611,20,561,112,3,88,167,66,129])

result.reverse()

print(result)

As you can see, the order of all the elements is reversed in such a way that the first element is the last and vice versa.  

Consequently, in this lecture, we have seen the details of arrays in a different way than when the introduction was done at the start. After that, we have seen what the workings of the contiguous memory location are and how it is different from the other types of contiguous memory locations. Different functions were also discussed in this regard, and more will be discussed in the next lecture. 

Python Dictionary Operations Using Jupyter Notebook

Hello peeps! Welcome to the new episode of the Python tutorial. We have been working with different types of data collection in Python, and it is amazing to see that there are several ways to store and retrieve data. In the previous lecture, our focus was on the basics of dictionaries. We observed that there are many important topics in the dictionaries, and we must know all of them to make our base of concepts solid. For this, we are now dealing with the dictionaries in different ways, and this tutorial is going to be very interesting because we will pay more heed to the practical work and, by choosing a few cases in our codes, we will apply multiple operations to them. So have the highlights of today’s learning, and then we will move forward with the concepts.

  • What are nested dictionaries, and how do we use them?

  • How do you access the elements in the nested dictionary?

  • Tell us the procedure to add and delete elements from the dictionary.

  • Can we modify the elements of the dictionary? If yes, then how can we do so?

  • What is the membership test, and what is the procedure to use it in the dictionary?

  • Write the simple example in which the iteration is used with the dictionary.

Nested Dictionaries in Python

In the previous lecture, we saw simple dictionaries and applied their functions to them. In the present lecture, the details of the dictionaries will be discussed in detail. These functions are not new to us but have been learned while dealing with sets and lists. Yet, the working and the results of every function are different with different types of data, and therefore, we are using the predefined functions again but with a twist. In the previous lecture, we saw the nested dictionary in an example but have not mentioned the details because we were discussing the list in dictionaries and it was not suitable to discuss it at that moment. Yet, have a look at the definition of a nested dictionary:

“A nested dictionary is a type of dictionary in Python that contains more than one dictionary separated by commas in it with different indexes, and each dictionary has a specific number according to its order.” 

Accessing the data is a little bit more difficult in the nested dictionaries than in the simpler ones because the index is so important. The dictionaries are then divided with the help of commas between them. Open your Jupyter notebook by following these steps:

  • Go to the search bar on your PC.

  • Search for the Jupyter notebook.

  • Now go to the drop-down menu and choose Python there.

  • Wait for the new local host to be opened in your browser. 

  • Go to the new cell and start coding.

Copy this code and paste it into the cell. By pushing the run button, you will get the perfect nested dictionary. 

Accessing the Data From a Nested Dictionary

Do you know the meaning of our statement that accessing the data from a nested dictionary is a little bit different? It is because we need to type more of the data, and therefore, it is important to mention all the information accurately, as with all types of data, and this becomes tricky for  non-programmers.

#Declaring the nested dictionary containing the information of the books in a library

bookData = {1: {'subjectName': 'Physic', 'coverColor': 'red', 'Pages': '125'},

          2: {'subjectName': 'Chemistry', 'coverColor': 'blue', 'Pages': '234'},

           3: { 'subjectName': 'Biology', 'coverColor': 'green and blue', 'Pages': '564'}}

#Printing the required value

print("Your required data = ", bookData[2]['coverColor'] )

So, as you can see, the real use of a nested dictionary is to get more readable and clean data every time. These are the advantages of the nested dictionary it is more practical, and a large amount of data can be stored and accessed easily. 

Addition of The New Element in Nested Dictionary

It is the plus point of the dictionary that programmers can easily add the element in the nested dictionary by using some simple steps. The point here is to e discussed is to show you that the concept of an empty dictionary is present in Python. Many other data types do not have this characteristic. Hence, the addition of a new element becomes easy while using the dictionary. Have a look at the output of the code and after that, we will discuss the points about it.

#Declaring the nested dictionary containing the information of the books in a library

bookData = {1: {'subjectName': 'Physic', 'coverColor': 'red', 'Pages': 12},

          2: {'subjectName': 'Chemistry', 'coverColor': 'blue', 'Pages': 234},

           3: { 'subjectName': 'Biology', 'coverColor': 'green and blue', 'Pages': 564}}

print("Dictionary before modification = ",bookData )

print()

#Making the room for the new element by creating the empty dictionary

bookData[4]={}

#inserting elements in the next space

bookData[4]['subjectName']= 'English'

bookData[4]['coverColor']= 'yellow'

bookData[4]['Pages']= 611

print("The modified dictionary= ", bookData)

We can conclude the following points from the data given above:

  • The addition of the new dictionary to the existing nested dictionary is easy.

  • There is a need for a blank element so that we may fill in the required items.

  • The programmer in the code has declared the number of the dictionary and not the index, therefore, the data is not started with a zero and instead, the numbers of our choice are used. The programmer may name its dictionary anything no matter if it is the number of the alphabet. 

Deleting the Dictionary from Nested Dictionary

Let us discuss the case in which the programmer wants to delete the whole dictionary from the nested collection for some reason. For this, the procedure is not too long and the simple delete command is used for it. For better elaboration, we are using the same example and deleting the second dictionary from our list.

#Declaring the nested dictionary containing the information of the books in a library

bookData = {1: {'subjectName': 'Physic', 'coverColor': 'red', 'Pages': 12},

          2: {'subjectName': 'Chemistry', 'coverColor': 'blue', 'Pages': 234},

           3: { 'subjectName': 'Biology', 'coverColor': 'green and blue', 'Pages': 564}}

print("Dictionary before modification = ",bookData )

print()

#Deleting the 2nd dictionary

del bookData[2]

print("The modified dictionary= ", bookData

Here, the question arises if the single element is to be deleted only, what will be the code? There are only minor changes in the code given above, and only the particular element of the mentioned dictionary will be deleted. 

#Declaring the nested dictionary containing the information of the books in a library

bookData = {1: {'subjectName': 'Physic', 'coverColor': 'red', 'Pages': 12},

          2: {'subjectName': 'Chemistry', 'coverColor': 'blue', 'Pages': 234},

           3: { 'subjectName': 'Biology', 'coverColor': 'green and blue', 'Pages': 564}}

print("Dictionary before modification = ",bookData )

print()

#Deleting the specific elements from the dictionary

del bookData[2]['coverColor']

del bookData[3]['subjectName']

print("The modified dictionary= ", bookData)

Modifying Data From Dictionary

The next step is to learn about the modification process of the dictionary, and for that, we are choosing another example because it is boring to check the conditions from the same example all the time. For the sake of simplicity, we are using the simple dictionary instead of the nested type of the dictionary.

#Declaring the initial data of the staff

staffInfo = {"2C32": "HR", "2C34": "Chemist", "2C20": "Doctor"}

print("Initial Staff Information: ", staffInfo)

#Changing the staff information 

staffInfo["2C32"] = "Compounder"

#Printing the results

print("Updated Staff Information: ", staffInfo)

Hence, in this way, we do not have to first delete and then add the new element in its place; simply changing the element is enough. The new value is masked over the previous one, and in this way, the task becomes easy.

Membership Test on the Dictionary

Until now, we have seen some simple and short examples so that the concepts may be easily understood. Yet you must know that in real-life applications, dictionaries are so large that it becomes difficult to notice the existence of specific elements in them. For such cases, it is important to learn the command to check the availability. 

# Membership Test for our new dictionary

AvailableFood = {1: "chicken", 2: "beef", 3: "barbeque", 4: "burger", 5: "soup",

                6: "salad", 7: "cake", 8: "lasagna", 9: "pizza", 10: "pie",11: "sandwiches",

                12: "pasta", 13: "mushrooms", 14: "sausage", 15: "ice cream", 16: "cola",  17: "cupcakes",

                18: "chocolate", 19: "biryani", 20: "golgappy", 21: "bread", 22: "jam", 23: "eggs" }

#Checking the availability by using just the key

print(6 in AvailableFood) 

#checking if the certain key is "not" available

print(18 not in AvailableFood) 

#Using a false value to check the behaviour of the keyword 

print(49 in AvailableFood) 

If we go into the details of this code, we may get the idea that:

  • Dictionaries can be used to store a massive amount of data. 

  • The addition of the data is so simple and uncomplicated, and we can access any element easily.

  • The keys are useful to get the data easily without any complexity in typing in such cases if we use the integers as keys. 

  • The “in” function searches for the required elements of the user and gives the result about the availability of the element. 

  • The “not in” function is totally opposite from the former case, and the programmer can use it to check whether the specific element is absent or not. 

  • The third case is interesting, we simply put the value to check how the “in” function responds when the element is not present in the dictionary, and the result was as expected.

Using the Iterations in Dictionary

The iteration process is fascinating, and we always try to provide you with examples that you will use in the practical implementation over and over again. The iterations are an important concept, and you will learn them in detail in the coming sessions, but we believe that, for now, you have an idea of what they are and how the programmers use them in their codes. It is time to check what the dictionary will do if we use it in the for loop. 

# Membership Test for our new dictionary

AvailableFood = {1: "chicken", 2: "beef", 3: "barbeque", 4: "burger", 5: "soup",

                6: "salad", 7: "cake", 8: "lasagna", 9: "pizza", 10: "pie",11: "sandwiches",

                12: "pasta", 13: "mushrooms", 14: "sausage", 15: "ice cream", 16: "cola",  17: "cupcakes",

                18: "chocolate", 19: "biryani", 20: "golgappy", 21: "bread", 22: "jam", 23: "eggs" }

#using the for loop with the "in" keyword to get the list of each and every food item

for element in AvailableFood:

 print(AvailableFood[element])

Hence, all the elements are printed one after the other in a new line, and the programmers can simply get the available food items by using a simple command.

For more practice, I want to check the behaviour of this loop when I use it with the nested dictionary:

#Declaring the nested dictionary containing the information of the books in a library

bookData = {1: {'subjectName': 'Physic', 'coverColor': 'red', 'Pages': 12},

          2: {'subjectName': 'Chemistry', 'coverColor': 'blue', 'Pages': 234},

           3: { 'subjectName': 'Biology', 'coverColor': 'green and blue', 'Pages': 564}}

print("Elements of the dictionaries = ",bookData )

print()

#printing All the dictionaries using iteration.

for myBooks in bookData:

 print("Elements of single dictionary using the for loop = ", bookData[myBooks])

The results of the code given above are clean and more understandable:

Hence, the use of iterations makes our output uncomplicated and ordered. So it was all about the dictionary in this episode of the Python programming language. It was amazing to see the different examples, and all of them were related to the dictionaries. The usage of the dictionary in Python is important to understand; therefore, we used the Jupyter notebook to access, add, delete, and modify the elements of nested dictionaries and simple dictionaries with the help of examples. Moreover, the membership test was also interesting to learn and easy. In the end, the iterations made our work easy, and we got a cleaner output with the help of the iterations. We hope it was an attractive way to learn the dictionaries and stay with us for more concepts of Python. Happy learning to all of you.

Dictionaries in Python using Jupyter Notebook

Hello students! Welcome to the new Python tutorial, where we are learning a lot about this programming language by applying the codes in a Jupyter notebook. It is interesting to see how simple codes with easy syntax can be useful to store, retrieve, and use data in different ways. Many things in Python are so unadorned and pre-defined that programmers may use them in a productive way without any issue. 

In the previous lecture, we have seen the details of the sets and how different types of mathematical operations are used to get the required results. We have seen many codes, the examples of which were taken from day-to-day life. In the present lecture, the mission is to learn a new topic that is related to the concepts of previous lectures. Yet, it is important to have a glance at the points that will be discussed in detail here:

  • Introduction to the dictionaries in the python programming language.

  • Why do we need dictionaries if we have different ways to store the data?

  • How can we use dictionaries in Jupyter notebook?

  • How do you define the concept of keys in dictionaries?

  • What are some characteristics that make the dictionaries different from others?

  • How do you justify that using the list with dictionaries makes the working better?

These points are the important interview questions and all of these will be crystal clear in your mind when we will go deep into these concepts one after the other. So stay in this lecture till the end and we will discuss the basic concept today.

What is Dictionary in Python?

To understand the topic, the first question that arises in the mind is what actually constitutes a dictionary and why it is important to understand this concept. An interesting piece of information to share here is that dictionaries are not new concepts; these were defined in the older versions of Python as well, but the difference is that in the older versions, from Python 3.6 onward, dictionaries were considered unordered, and if we talk about the current introduction, we will get the following lines:

"In Python 3.6 and later, a Python dictionary is an ordered collection of data that stores data in the form of pairs in keys or values."

The word  “ordered” is not new to us and from the above information, we can understand that in the older versions of Python dictionaries when displayed in the output, does not have the proper indexing and the order of the element was unpredictable but when talking about the updated version (that we are using during this tutorial) the order of the elements in the dictionaries is well defined and the elements will be arranged in the same manner always that is defined by the programmer. Here it is important to notice that usually, the students are using the updated version of Python and there is no need to mention the older versions but the reason to mention this is, the older versions are preferred by the users that have older personal computers or because of any other reason, if they are using the previous versions, then they will find the dictionaries a little bit different from this tutorial. 

Why We Need Dictionaries?

We have been working with the data types in Python that all are used to have the collection of data and the question here is why we need another entity that can store the data if we have lists, sets, and others. The answer here is simply because the way to store the data is different for all of these and as the topic of discussion today is dictionaries, you must know that it uses the key values to store the data and therefore, it becomes uncomplicated to store the data using the key value mapping format. The most common advantage is, the retrieval of data from the dictionary becomes super easy with the help of these key values. If we talk about the complexity of the dictionaries, we will get the following data:

  • The best case of a dictionary has O(1) complexity.

  • The worst case of a dictionary has the O(n) complexity. 

Using the Dictionaries in Jupyter Notebook

Now, that you understand the basics of dictionaries, to make the discussion clear, examples are being used in the Jupyter notebook. We have been using it in our tutorial, and therefore, we know that we simply have to start the software and get the new tab in the browser by clicking on the “new” dialogue box and clicking on “Python 3." 

Once you get the worksheet now it's time to get used to all the codes that will clarify the concepts in a better way. So let’s start learning the concept and then simply use all the learning in our codes. This will be easy to understand because we have been working with such types of codes in this whole course but the difference here is the key of the dictionary. 

Concept of Keys in Dictionary

You must know that dictionaries are declared by using the curly brackets in Python and if you have seen our previous tutorial, you must have the idea that the same representation was used in the sets then how can the compiler differentiate between these two and what is the reason to introduce the concept of dictionary in Python? Well, as we move towards the complex problems, we get the idea that simply storing the data is not enough, there is a need of providing the reference of the data and this happens when we use the keys in dictionaries.

“A key in Python dictionary is the specific and unique value assigned to each element and that has the immutable data type.”

The role of keys in the dictionaries will be clear by using the output of the code given next:

#declaring the dictionaries containing the grocery items

GroceryItems={"lettuce":4, "onion":34,"pepper":8,"plum":12, "frozen fruits":22}

print(GroceryItems)

Hence, the keys add more details to the dictionaries, and the data is stored in a better manner while being used in dictionaries. The usage of the keys is still ambiguous in the mind, hence, we are using different examples to express it well. There are different ways to use the dictionaries, and these procedures are given next:

#declaring the dictionaries containing the grocery items

GroceryItems={"lettuce":4, "onion":34,"pepper":8,"plum":12, "frozen fruits":22}

print(GroceryItems)

#retriving the data using the concept of keys in a dictionary

print("The required data = ", GroceryItems["pepper"])

Hence, the data stored in the key can be used easily to retrieve the data. In the example given above, when the person wants to get the number of groceries they want with the help of items. 

Characteristics of Dictionaries

We have focused on the examples, but before going into the details of them, you must know some important points about the dictionaries.

  • The dictionaries are declared with the help of curly brackets. 

  • The keys are used with the elements and to declare them, the colon is used along with each element. 

  • The value of the keys can be obtained by mentioning the element. 

  • The dictionaries are ordered and every time when the same dictionary is declared, we get the element as same as that was mentioned in the code. 

  • The usage of any data type is allowed in the dictionaries, and therefore, the working of a large amount of data is possible in the dictionaries. 

  • Same as the sets, duplicate elements in the dictionaries are not possible. It means when the element is repeating in the code, the compiler automatically ignores the second third, or any type of repeating of the same element and therefore, the repetition is not allowed in dictionaries. 

Let us now look at some examples of dictionaries where we will use our Python concepts and some functions to interact with the dictionaries. 

Using List with Dictionaries in Python

We know about the details of lists in the Python programming language, and now we want to connect things together so that we may understand why the students had to learn a lot about lists. Python provides uncomplicated ways to use different functions and concepts and get useful results. In the Jupyter Notebook, we are now inserting the list into our dictionaries in two ways, and in this way, the concepts of lists will also refresh our minds. 

Inserting the List as an Element in Dictionaries

During discussion about some important characteristics of dictionaries, it was mentioned that any data type can be inserted into the dictionaries, and this point will be proved with the help of the following code:

#declaring the dictionary of tooth brush 

toothBrush = {

  "Name of Item": "toothbrush",

  "electric": False,

    "price": 60,

  "available colours": ["red", "white", "blue"]

}

print("Features of tooth brush in detail: ",toothBrush)

print("Price of the tooth brush= ", toothBrush["price"])

When we input this code in the new cell of our local host, after pushing the run button, the following results can be obtained:

Hence, it is proved that any data type in Python can be inserted into the dictionary, and this characteristic gives the programmers the independence to use the collection of data and relate it to a single item in the dictionary. In the example we have just seen, there were multiple options for the same brush about its colours, and hence, in such cases, the programmers use dictionaries to get the required results.

Using the Dictionary in List

Here comes a different kind of concept that we have not learned in this tutorial until now. The list can also have the dictionaries as the element and if you are wondering why the programmers use them then you must know, the characteristics of the data types matter, and each data type has its own speciality therefore, the combination of both these data types in different ways gives us the variety of uses. 

#Create a list of dictionaries that represent the prices of different items

#along with their serial number in the grocery store.

myStoreItems = [{345: 'chicken', 567: 'eggs',

                 561: 'beef', 879: 'mutton'},

                {348: 'milk', 670: 'butter',

                127: 'bread', 445: 'tea bags'},

                {237: 'chocolate spread', 381: 'jam',

                 890: 'sauce', 340: 'sandwich'}]

 

print(myStoreItems)

#accessing the data from the first dictionary

print("The required item is ",myStoreItems[0][561])


#accessing the data from the second dictionary

print("The required item is ",myStoreItems[1][127])


#accessing the data from the second dictionary

print("The required item is ",myStoreItems[2][340])

In this way, we can extract the following concept from this code:

  • The dictionaries can be used in the lists.

  • There is the possibility of using different dictionaries in the same code.

  • The data can be accessed from any dictionary by using the index of the data.

  • To get the exact element, the programmers have to write the index of the element. 

  • For using the right indexing method, first, we have to mention the dictionary number and then the key of the element. 

  • It's a reminder that indexing starts at 0. 

  • It becomes easy to manage the data with the keys and more data can be stored in a single dictionary in a more manageable way. 

  • The declaration of the dictionaries resembles the sets and we see many features of these two concepts that resemble each other. 

In this lecture, we started our discussion with the introduction of dictionaries. The list has many informative features, and the combination of dictionaries with the list makes many useful tasks easy to complete without facing any issues because of the smooth process. The user simply has to feed the required data, and at the appropriate time, the data can be retrieved easily. So, that was all for today. Dictionaries have applications in different ways, and therefore, it is not possible to provide students with all the necessary information in a single lecture. Therefore, in the second part, we will discuss more details about dictionaries and learn a lot through examples.

Set Sequence Examples with the Built-in Function

Hey people! Welcome to another tutorial on Python programming. We hope you are doing great in Python. Python is one of the most popular languages around the globe, and it is not surprising that you are interested in learning about the comparatively complex concepts of Python. In the previous class, our focus was to learn the basics of sets, and we saw the properties of sets in detail with the help of coding examples. We found it useful in many general cases, and in the present lecture, our interest is in the built-in functions that can be used with the sets. Still, before going deep into the topic, it is better to have a glance at the following headings:

  • What are the built-in functions?

  • How do we perform the all() function with examples?

  • What is the difference between any() and all()?

  • What are the parameters of sorted()?

Built-in Functions with Sets

From the beginning of this course, we have been using the built-in functions for different purposes, but here, the main idea must be cleared, so for the purpose of revision, have a look at the basic definition of these functions:

"Built-in functions are the pieces of code that have a particular result all the time and are pre-defined in the programming languages so that the programmer does not have to type the same code but simply put the values in the functions and get the required output as expected with minimum effort."

For a better understanding of the sets and the practice of these in codes, the best way is to use the built-in functions so that whenever you are coding these built-in functions arise instantly into your mind and the effort to code the same line again and again in different programs. There are certain types of built-in functions, the details of which were covered in the previous lecture, so for now, we are trying to introduce the new functions and repeat just the most common ones with the sets.

all() Function with Sets

The first function of discussed by us is very interesting and has application in many general cases. This function checks the element of the set one after the other and on the basis of a combination of results, it provides the output. The working of all() is a little bit tricky. Consider the case when we define a set with a particular data type and all function and then keeps that data type in the memory. Afterwards, it checks the result by following the sequence of combinations and then provides a single output in the form of true or false. The combination of all() is given in the table:

True

False

Result

All values

No value

True

No value

All values

False

One value

Remaining

False

Remaining

One value

False

Empty set

True

Hence, just like the logical gates, the all() function works on the logics, and this will be proved when you see these examples:

all() Examples in Set

Before going into the details of the all() function, have a look at the code where only integers anf floats are used with different values.

# integer set with non-zero values

myIntegerSet = {33,6,5,12,44,9}

print(all(myIntegerSet))

# Float and false value

myFloatSet = {33.6,55.9,12,4, False}

print(all(myFloatSet))

# Float with only one false value

FloatWithOneFalse = {1.8, 3.55, 4.34, False}

print(all(FloatWithOneFalse))

# Integer set with only one true value

integerWihOneTrueValue= {44,False,0}

print(all(integerWihOneTrueValue))

# empty set

emptySet={}

print(all(emptySet))

The following points are extracted from the results given above:

  • The digit zero is always considered false if you are using the float or integer sets. 

  • The all() function checks each and every element and stores the results in memory, then checks for the combination and provides the results. 

  • It is obvious that if the set contains the value "false,” then it will be considered the false function, and the compiler will not consider it a string. 

  • The empty set is always true. 

Exercise

Now, this can also be performed with the string sets, and all the strings will be considered true. Hence, any element with double quotation marks will be considered a string, and the compiler will provide the output in the form of a single result. 

Your task is to design the code using the information given above and check the results by matching the table given above. 

any() Function with Set

If you have understood the previous function, then this will be more fun for you because, in some cases, we can say that the any() function is the opposite of the all() function. Therefore, they are named so. So, look at the code of the any() function, where only the name of the function is being replaced, and you will see the clear difference in the results.

# integer set with non-zero vlaues

myIntegerSet = {33,6,5,12,44,9}

print(any(myIntegerSet))

# Float and false value

myFloatSet = {33.6,55.9,12,4, False}

print(any(myFloatSet))

# Float with only one false value

FloatWithOneFalse = {1.8, 3.55, 4.34, False}

print(any(FloatWithOneFalse))

# Integer set with only one true value

integerWihOneTrueValue= {44,False,0}

print(any(integerWihOneTrueValue))

# empty set

emptySet={}

print(any(emptySet))

The results can easily be understood, and this time, we have extracted the table of combinations from the output of our code:

True

False

Result

All values

No value

True

No value

All values

False

One value

Remaining

True

Remaining

One value

True

Empty set

False

So, the same task is for you as we have given the exercide with the all() function. 

enumerate() Function with Set

It is a different kind of function and is meant to represent the set in a better manner. While using it with the set, the output is obtained has the number of index with it automatically. It is useful in the long sets where the number of elements matters, and by using this, the programmer does not have to do the counting manually, but the index number is shown with each element. For this, the results are saved into the variable, and then the results are fed into the list. If it is confusing at the moment, have a look at the code given next:

#Making the set of books

Books={'Biology', 'Chemistry', 'Physics', 'English', 'General Knowledge', 

       'geography', 'poems', ' grammer','programming', 'software', 'technology'}

#declaring the varialbe

i=enumerate(Books)

#using the varialbe in list and printing the results

print(list(i))

So, all the books are arranged and have an index according to their position. Take the case into your mind, where the set contains hundreds or thousands of elements, and the indexing helps us to understand the collection.

sorted() Function with Set

The next function that is going to be discussed is the sorted() function, that plays an important role in the numeric calculations. Usually, programmers feed the data in an unordered manners. 

Example of Sorted() Function

If all the discussion above is not enough for you to understand the whole concept, then do not worry because these examples and their explanation will help you understand the concepts deeply. 

Sorting of Numbers

It is a simple task, and the sorting is easy when you have few elements, but with the complex cases, the sorting needs logic. You will see some examples with the parameters in the same lecture, but for a start, have a look at the code below:

So, the sorting process of integers and

#Declaring the set

print("The unsorted set = ", myIntegers)

print()

#Using sorted() function on the set

print("The sorted set= ", sorted(myIntegers))

This is the big array, and it is difficult to arrange it manually; therefore, we are using sets here to eliminate the duplicate elements and to sort them with the help of a simple command.

Once the set is complete, it becomes difficult to read and understand the data of the set if it is large. In such cases, the sorted function is used, which sorts, or, in simpler words, arranges the data into a specific order. To learn about the syntax of this function, you must know three parameters:

Iterable Parameter in sorted Function:

This is the general term used to present a collection of things, groups, loops, or sequences. These are the necessary parts of the sorted function, and as “set” is the collection of data types, we can use it in this function to sort the elements according to our wishes. Without this parameter, the compiler will show the error. 

Key Parameter in Sorted Function:

It is a relatively difficult parameter to grasp, but it is responsible for the function's versatility. It may be tedious to realize that the set you are entering is only sorted in ascending and descending order. In programming, the data is stored in the form of different collections of numbers, and the key is the way to tell the compiler which pattern must be followed for sorting the data. This will be clear with the help of an example, and after that, we will examine the results:

Reverse in sorted() Function:

The second parameter in the sorted() function is optional, and it is used to ask the programmer about the way to sort the data, that is if the programmer needs the iteration in an ascending or descending manner. It just has two possible inputs: true or false. As the name of the parameter indicates, if the reverse is set to true, the results will be in reverse order, that is, from the highest value to the lowest. But by default, it is always true, and if the programmer inputs true or even does not use this parameter, the output of the set will be in ascending rather than descending order. 

# My string list declaration

mySet ={ ('apple'), ('red'), ('black'), ('strawberry')}

# sort set taking length as key and reversing the order

Result = sorted(mySet, key=len, reverse=True)

# print set

print('Sorted results:', Result)

So, it was an interesting tutorial on the sets, and with the help of different examples, we have learned built-in functions such as all(), any(), and the sorted function.

Python Set Operations with Examples

Hey, learners! Welcome to the next tutorial on Python with examples. We have been working with the collection of elements in different ways, and in the previous lecture, the topic was the built-in functions that were used with the sets in different ways. In the present lecture, we will pay heed to the basic operations of the set and their working in particular ways. We are making sure that each and every example is taken simply and easily, but the explanation is so clear that every user understands the concept and, at the same time, learns a new concept without any difficulty. The discussion will start after this short introduction of topics:

  • How do we declare and then find the difference between the two sets?

  • What are the built-in functions for operations, and how do we use them in the codes?

  • How do we apply the operation of symmetric differences on the sets?

  • What is chaining in iteration, and how do we use it? Give some examples.

  • How do you define the union of the sets?

  • What is an intersection and how it is related to the sets?

  • What is the procedure to find whether the sets are equal or not? Give us some examples in Python.

All of these are important interview questions, and we are using the concept in this lesson to find the answer to each question in detail. The Jupyter notebook is being used for practical work. To open it, go to the search bar in Windows and search for the Jupyter notebook. After that, go to the “new” dialogue box and start Python 3 to create a new notebook. 

Why Mathematical Operations are useful in Coding?

We all come from a programming background, and it is not surprising to know that different mathematical operations are used in programming to do useful tasks. In this lecture, you will learn the importance of mathematical functions with regard to sets. We have been working on the set since the last two lectures, and we are now aware of the details of working on sets. But during the programming process, the code contains different types of calculations, and large programs are extremely difficult to run without the involvement of mathematical operations. We will explain this with the help of different examples, and this is going to be fun because these concepts have been studied by us since our early education, and now is the time to know the reasons for that study.

Difference Between Two Sets

This is the simplest set operation and it involves the difference between the elements of the set in their corresponding values. In simple words, if we are dealing with two sets named A and B then the difference between them is a new set containing all the elements that are in set A but not in set B. In Python, there are two ways to get the difference of the set in two ways:

  1. The difference using the sign

  2. The difference using the function

Both of these are discussed in detail here. The difference with the sign is simple as we minus the values in the simple mathematical question. A minus sign is used between the names of the set, and we get the result. 

On the other hand, if we talk about the function, Python has a built-in function that calculates the difference, and it is a more professional way to use the functions for such operations. These two methods are simply described in the example given next:

#Declaring two sets

A={12,8,34,5,90,3,2}

B={1,7,90,33,2,1,5}

#Using both methods of difference 

differenceWithSign=A-B

differenceWithFunction=(A.difference(B))

#Printing results

print("A-B= ",differenceWithSign)

print("Difference with function= ", differenceWithFunction)

It is obvious that both methods give us the same results. So it totally depends on the programmer to choose the method, but here is a reminder that the order of the names of sets is important here because if we write B-A then the results will be entirely different. 

Set Symmetric Difference 

If you found the difference between the sets easy then you will find it more interesting because it is similar to the difference of the set but the only change is, in the resultant set, the uncommon elements of set A and B both are included instead of only the first set. In this way, the output of the entries from both the sets and no set is ignored. To denote the symmetric difference, the “^” sign is used. By the same token, the function for the symmetric difference also exists in Python,n and the keyword “symmetric_difference” is used for this. Have a look at the code and output for this case:

#Declaring two sets

A={12,8,34,5,90,3,2}

B={1,7,90,33,2,1,5}

#Using both methods of symmetric difference 

SymmetricDifferenceWithSign=A^B

SymmetricDifferenceWithFunction=(A.symmetric_difference(B))

#Printing results

print("A^B= ",SymmetricDifferenceWithSign)

print("Difference with function= ", SymmetricDifferenceWithFunction)

Compare the results with the previous operation, and the difference will be clear.

Chain with Sets

In the previous lecture, we have been working with the itertools. The current case is to check whether the itertool works with the sets or not. You will see that the union of the two sets has the same results as the chain of the two sets, but for the sake of learning, we are working on both concepts. Hence, have a look at the code and understand it. After that, type the code on your own and check the results.

from itertools import chain

apple={12,8,34,5,90,3,2}

banana={1,7,90,33,2,1,5}

totalSales=set(chain(apple,banana))

print(totalSales)


By simply declaring and using the sets in a chain format, we are getting the result of the sales of both fruits, but in the cases where both sales were equal, the entry is ignored as we are using the set that ignores the duplicates.

At the simplest level, the results of union and chain are the same, but at a higher level, the working of both of these is different; therefore, it is important to understand both concepts and practice them with the sets. 

Now, let us show you an interesting example of the same function where a set is used with the string entries. When applying the chain to that particular set, the same alphabets are ignored. The programmers can represent the results as joining or separate results, and this is explained well with the following code:

from itertools import chain

A = "Python"

B = "Programming"

C = "Tutorial"

output1 = set(chain(A, B, C))

print("before joining the set :", output1)

output2 = ''.join(res)

print("After joining the set :", output2)

We know the message is not conveyed in detail and therefore, it is proved that sets are more useful when dealing with numbers. 

Union of the Sets

The name of this operation is self-explanatory if we have two sets named A and B, then the union of these sets means a new set that contains all the elements of set A and set B. We have read this in our mathematics classes, but here, this will be done with the help of coding. There are some special signs that are used to define the operations, just like we indicated the difference with the help of minus signs. When we talk about the union of the sets, we use the | sign for this, and Python also has the function for the union. 

There is no need for long explanations for this operation, and we are simply changing the sign of the previous example and providing you with an example of how the difference and union give you entirely different results by changing just the operation. 

#Declaring two sets

A={12,8,34,5,90,3,2}

B={1,7,90,33,2,1,5}

#Using both methods of Union

unionWithSign=A|B

unionWithFunction=(A.union(B))

#Printing results

print("A | B= ",unionWithSign)

print("Union with function= ", unionWithFunction)

As a result, the resultant set contains the values of both sets, but have you noticed that the resultant set has fewer values than the collection of both sets A and B? It is because we are using sets, and the values that are identical are just shown once.

The Intersection of the Sets

If you have understood the concept of the union of sets, then you must keep it in mind, and then by comparing the process of intersection, the concept of both these operations will be clear in your mind. It is because usually people seem confused between these two. 

Let us take the case where we are discussing the recipes of two dishes that are chicken and fish and want to know the common ingredients to write in the list. For this, we will use the intersection of the set, and both of these will contain the name of the ingredients, which means these are the string sets. During the process of the intersection of sets "fish” and "chicken," the resultant set contains all the elements that are common in both sets, and all other entries are totally ignored. In this way, the person will be able to understand what things he needs from the same section of the store and where he has to go for more shopping. This will be done with the help of the following code: 

#Declaring two sets of string

fish={"Onion", "Tomato", "Garlic", "Fish", "Salt", "Carrot", "Eggs", "Ginger"}

chicken={"Chicken", "Salt", "Potato", "Onion", "Garlic", "pepper"}

#Using both methods of intersection 

intersectionWithSign=fish & chicken

intersectionWithFunction=(fish.intersection(chicken))

#Printing results with the same ingredients

print("fish & chicken= ",intersectionWithSign)

print("Intersection with function= ", intersectionWithFunction)

Equality of the Sets

When dealing with different types of sets, let's say set Apple and set Banana, where the shopkeeper stores the data of the weekly sales of cartons, the seller wants to take the record of the day and check if the sales are the same or not. Then, he simply checks the results by applying the equal signs for the two times between the sets and getting the result. Keep in mind that the order of the set does not matter here as the set does not have the index values. So, no matter if the sales were not equal on the same day, if the weekly sales are matching exactly, then the sets will be equal. 

#Making the set of apples and banana with the sales

apple={34,78.9,32,89.7,33,12.6,55}

banana={12.6,78.9,33,34,32,89.7,55}

#using if loop to check the results and print the output

if apple==banana:

    print("Sales of apple and banana are the same")

else:

    print("Sales of apple and banana are not the same")

Now, to elaborate on this more, the sets that are used in the previous examples are fed into the same code, and then by running the code, we can conclude the results. 

#Making the set  with the sales

apple={12,8,34,5,90,3,2}

banana={1,7,90,33,2,1,5}

#using if loop to check the results and print the output

if apple==banana:

    print("Sales of apple and banana are the same")

else:

    print("Sales of apple and banana are not the same")

The “if” loop is an important iteration, and this is the best way to explain how we can use it for the bi-conditional cases. These loops will soon be used in many complex codes in this tutorial.

 

Hence, it was a fantastic tutorial on sets, and we learned a lot with the help of different operations. We had an idea about the sets and their characteristics, but in this lecture, the operations and working of the sets are well explained, and we see the difference, symmetric difference, chain, union, intersection, and equality operations of the sets in detail. I hope you get the point that we are trying to make clear. For more interesting tutorials, stay on the same website.

Sets in Python using Jupyter Notebook

Hello students! Welcome to the new tutorial on Python. We all know that Python is one of the most popular programming languages, and there are hundreds or thousands of developers that are earning a handsome amount with the help of this easy programming language. In the previous lecture, we studied the range in the sequence, and in the present class, our concern is having the command on the sets in Python. We know you are curious about the set's details, but before this, I want to share the list of topics that will be covered in this class.

  • What is a set in the Python programming language?

  • What are some properties that distinguish the set from other data types?

  • What is the mutable data type, and how is it related to the set?

  • Introduction of the Jupyter notebook.

  • Can we have duplicate elements in the set?

  • How to add, remove, and update the elements in the set while using the Jupyter notebook.

  • How can we access the elements using a loop?

  • Give an example of how to use the length function with sets and why it is important.

All of these are important interview questions, and we will not only find the answer to them but also elaborate on them with the help of simple but understandable examples taken from daily life routines. Your duty is to perform each and every code, not only by copying it from the lecture but also test your knowledge and practising more and more by making your own examples.

Introduction to Sets in Python

Since the last few tutorials on Python, we have been studying a lot about the sequence, which is basically the representation of a collection of data types with homogeneity or heterogeneity in the elements. If we talk about the sets, these have the same properties and procedures as their other group, such as list and range, but a slight difference in their property makes them a different data type. This can be elaborated with the help of its basic definition:

“The set is the type of sequence that contains the group of different data types, and it is the collection of unordered or unindexed data types together.”

Until now, the sequence discussed had been represented exactly as it was written by the programmers in the code. Yet, in the sets, the order is not exactly the same all the time. If you are thinking it is strange, then you must know, in the higher level of programming, this property of the set works great because we get the elements in random orders. 

Another difference between the set and the other sequences is the usage of the bracket, or, in other words, the declaration of the sequences. To tell the compiler that we want a set in the sequence, the programmers use curly brackets. You must have noticed that it is very rare to use curly brackets in Python, and therefore we can say that the representation of the set in Python is unique. 

Properties of Set Sequence in Python

As we have a lot of information about the sequences, we can openly discuss the properties of the set, and the reader will easily understand them by comparing them with others. So, here are some of the properties that can be compared:

  • Sets are represented with curly brackets. 

  • The elements of the set can not be duplicated; that is, all the elements are uniquely defined, and no element should be repeated; otherwise, the compiler will show the output in which the duplicate values are shown only once.

  • The set is a heterogeneous collection of elements, and therefore, the programmers can add one or more data types to a single set according to their choice. 

  • The set can be empty, that is, declared with zero elements. 

  • The set can be updated after its formation if the programmer wants to make some changes to it afterwards.

  • There are certain built-in functions of the set that, when used with the sets, have great applications in Python programming.

Each of these properties can be explained well with the help of TensorFlow. We have been using the Jupyter lab of TensorFlow since the start of this tutorial, and now, I want to tell you a better and more professional way to run the code with the help of TensorFlow. For this, you do not have to install any other software but the Jupter notebook already installed on your PC. Simply go to your search bar and run the Jupyter notebook. It will add a new tab with the label "home." Here, go to the “New” dialogue box and select Python 3. This will add the new project to a new tab. You can name it, but by default, it is named "untitled." 

If you are practising all the codes with us by hand, you will observe that the Jupyter notebook has a better user experience, and it adds the ending of common syntaxes such as the double quotation and parentheses by itself when the programmer starts them. We will talk more about it in later lectures, but for now, we are moving towards the codes and properties. 

Sets and Mutable Objects in Python

The first thing that we want to revise here is the definition of mutable elements:

“In programming languages, mutable objects are those that are used to group different items and can change their value according to the instruction of the programmer.”

We have learned many mutable sequences, such as lists, and here, the point is to revise it to a set and not use the mutable sequences as the elements. Only data types such as strings, integers, etc. can be used as the elements in the set; otherwise, the programmer will face an error. This can be explained with the help of the code given below:

#Starting new list

myList=["Physics", "chemistry", "biology"]

#declaring a new set

mySet={myList,'a','e','i','o','u'}

print(mySet)

As a result, it is demonstrated that programmers can combine simple data types into sets, but it is not possible to create collections of mutable objects or collections of collections within sets. 

Duplication is Not Allowed in Set

In the properties, we have mentioned that the process of feeding the duplicate elements into the set is not useful because it checks for each and every element while providing the output, and if the element is being repeated, the sets ignore them. As a result, if we have the element more than once in our input, the number of elements in the input and output are not the same.

#Declaring the set

MySet={21,23.6,55,'Peach', 'Almond', 23.6,21,'Almond'}

#using iteration to print the set

for item in MySet:

 print(item, end=" ")

print()

#calculating the length

length=len(MySet)

print('Numbers of elements = ',length)

This property will be more clear with the help of the following screenshot:

Hence, out of eight elements, the two duplicate elements are removed by the compiler, and we only get five elements that were calculated by the length function.

Addition Method in Set

This is an interesting method that is compatible with the set in Python. Consider the situation where the programmer has declared a set and then needs to add an element to the same pre-defined set. In such cases, the addition method is useful, with the help of which the programmer simply uses the syntax of the add method and there is no need to recreate the whole set again.

NameOfSet.add(element to be added)

If the question arises about the position of the element, this will be clear with the help of an example that we are going to check:

#Initializing the set

mySet={'eggs', 'bread', 'jam',23,67,132,55}

print('Elements of my set is= ', mySet)

#adding a new element

mySet.add("oats")

#printing the set with the added element

print('Elements of my set with new element= ', mySet)

Removing the Element From Set

Keep the scenario in your mind that we have discussed above, but this time, there is a need to remove the lament from the set, and for this, Python has another method that simply searches for the required element from the set and removes it. Afterwards, the results can be printed on the screen to check whether the task is complete or not. The keyword to remove the element is "discard,” and it is used in the same way as the add keyword. 

#Initializing the set

mySet={'eggs', 'bread', 'oat','jam',23,67,132,55}

print('Elements of my set is= ', mySet)

#removing the element "oat"

removeValue=mySet.discard('oat')

#printing the set with the removed element

print('Elements of my set with discarded element= ', mySet)

So, the removal process is also very simple and understandable but the syntax must be kept in mind and before using the final set in this case, always check for the results by printing the elements on the screen as we are doing here because a little mistake on the syntax results in no removal and it may cause the problem in the code. So it is a good practice to have an eye on the elements.

Updating the Elements of the Set

The updating process of the set may include different types of updates, such as increasing the size or changing the elements' sizes. For a better understanding, the best way is to learn how two or more sets can be merged into one large set. In the previous lectures, we have seen this type of process where merging is done with the help of a method. To discuss a new method with you, here we are using the update method. The process and syntax are the same as we have seen in the previous two methods.

setToBeAdded.update(setToBeUpdated)

As a result, the final set has elements from both of these sets. But it is important to notice that both sets have to be declared first, and in the third step, we get the merged or updated search with the help of the command given above. 

#Initializing the first set

myFirstSet={'eggs', 'bread', 'oat', 'jam',23,67,132,55}

print('Elements of first set is= ', myFirstSet)

#Initializing the second set

mySecondSet={'Python', 'Java', 'C++'}

print('Elements of second set is= ', mySecondSet)

#Updating the sets

myFirstSet.update(mySecondSet)

#printing the final set 

print('Elements of final set= ', myFirstSet)

Hence both of these are merged together and as we are using the sets, the order of the final set is different and unarranged. Well, it is a good practice to check for the numbers of elements using the length function all the time.

For Loop in Set

We hope by now you have an idea of the for loop and how we use it with different data types in Python. Similar to the list, the programmers can access each and every element with the help of iterations (loops). So, let us review the elements of a set with the help of the for loop. 

#declaring our set with the name to-do list.

ToDoList={'assignment', 'coding', 'prayer', 'washing cloths', 'doing dishes'}

#starting for loop

for work in ToDoList:

 print(work, end=" ")

If we look at the output, we get the following results:

Hence, it was an interesting tutorial on the sets where we learned a lot about the topic and the details were interesting and related to our daily life. At the start, we saw the basic definition and a brief introduction to the topic. We have seen some properties of the sets that were resembling the types of sequences but these were also different in many ways and we not only studied them in detail but practically proved them in the Jupyter notebook. It was nice to use the Jupyter notebook that we are going to use onward in this series. In the next tutorial, we will put light on some other features so stay tuned with us because we are preparing our next lecture on Python.

Syed Zain Nasir

I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

Share
Published by
Syed Zain Nasir