30 Python Beginner Interview Questions & Answers
1. What does it mean by stating that "python is an interpreted language"?
This question is more of a general computer science question rather than a python question. The interviewer wants to determine if you know the process that takes place once you run your code. Knowing this process makes you a better developer and more likely to identify a problem if an error is returned.
We should first state the difference between Interpretation and Compilation.
For simplicity, we can say that Interpretation is the process of executing instructions directly and freely, without previously compiling a program into machine-language instructions.
Meanwhile, the compilation is the process of expressing the code instruction into machine-language instructions, then you can run it only after successful compilation.
Python is an interpreted language. Python interpreter converts the code to what is called bytecode. Then, instead of translating it to machine-language instructions, the bytecode instructions are executed on a Virtual machine.
Bytecode is a low-level set of instructions that can be executed by an interpreter. In most PCs, Python interpreter is installed at /usr/local/bin/python3.x. x is the python version installed on your PC.
Written by Aiad Asaad on April 15th, 2021
2. Imagine multiplying a string by a number in Python. Will this operation return an error? If yes, why? If no, what is the output?
This question is to test the knowledge about dealing with string and numbers together.
No, there will be no error. The output is just repeating the string n times where n is the number multiplied by the string. An example is in the code below:
a='ab' * 10
Here the "a" variable will be a string of "ab" repeated ten times. Therefore, it will be a='abababababababababab'
A technical interviewer will aim to determine if you can reason what happens when you mix types within python.
Written by Aiad Asaad on April 15th, 2021
3. How to remove the leading and trailing whitespaces in Python?
This question is to test the knowledge about Python methods.
This can be done by using strip(). It is a method that removes any starting and ending whitespace in a given string. The code below shows how to use it.
str= " It is a python interview "
final=str.strip()
If you run the code and print the final, you will see the final="It is a python interview". It has stripped away all whitespace from beginning and end.
Written by Aiad Asaad on April 15th, 2021
4. Using list comprehension, write a code that extract the upper case letters in a given string.
This question tests how to write code shorter simpler code.
The answer is in the code below:
s = 'AkilASidsaDJ'
uppers = [c for c in s if c.isupper()]
uppers
The method named "isupper" checks if the letter is uppercase. Then, if it is true (the letter is uppercase), and the letter is put on the list.
Therefore the uppers will be ["A", "A" , "S" , "D" , "J"]
The list comprehension uses a for loop and if statement and the isupper() built in function to return the result. All within one line of code. This impresses technical interviewers as it shows that you do not write verbose code.
Written by Aiad Asaad on April 15th, 2021
5. What is list comprehension in Python? Provide general structure to a list comprehension.
The list comprehension is a favourite for technical interviewers. It demonstrates that you know enough about lists, for loops and functions as well as having the ability to write short simple code.
List comprehension is a shorter syntax when you want to create a new list based on the values of an existing list or a loop.
General structure: newlist = [expression for item in iterable if condition == True]
Many developers new to python will create a function with a for loop that iterates over the list and appends the new data into a new list however the list comprehension does away with the need to write so much code.
It is worth practicing list comprehensions as they are frequently asked in technical interviews.
Written by Aiad Asaad on April 15th, 2021
6. What is the "pass" keyword?
This interview question is to test the knowledge about specific keywords in python.
"pass" is the same as a comment, but the interpreter recognizes it so it is used as a placeholder for future implementation of functions, loops, etc.
def my_function():
#nothing
def my_function_pass():
pass
The first function will result in an error as there is no code body for it. However, the second one named my_function_pass will run without any error because it was told what to do: "pass".
The pass keyword is useful when first outlining what functions you think are required for a particular task. It allows you to edit your code without forcing you to build each function at the very beginning of the process.
Written by Aiad Asaad on April 15th, 2021
7. What is the "assert" keyword in Python?
This interview question is to test the knowledge about the "assert" keyword in python.
"assert" is simply a debugging keyword. It works just like an "If" condition.
It tests if a condition is true. Otherwise, it returns an assertion error that can be controlled. It's heavily used inside the function structure. A simple code below shows how to use it.
x = 5
assert x % 2 == 0, 'x should never be even!'
It tests if the remainder of x divided by 2 is zero then it is okay. If not, then do the statement after the comma. Therefore, the output will be an error stating the 'x should never be even!
This keyword is particularly useful to automatically check if a condition is satisfied or else a customizable error is thrown.
Written by Aiad Asaad on April 15th, 2021
8. In case of naming a variable with the reserved name of a Python function, will the code run correctly at the first time? Will it also run correctly multiple times?
In python, there are a number of "keywords" that are reserved. This means we cannot name a variable one of these keywords.
The keywords are reserved for a reason as they have a predefined function within python.
Some of the reserved names are the names of the built-in functions such as "max", "min", "reverse" and "pop".
In case of naming a variable with one of the reserved names, as in the code below:
my_list = [4, -5, 9, -1, 45]
max = max(my_list)
It will run correctly for the first time. However, the second time, it will crash (get an error) because we named a variable with a reserved function name which overwrites the function. Hence, the second time (or any other next time), the default of the name belongs to the variable, not the built-in function. So, we can't call it. The type of error would be an object that is not callable.
Written by Aiad Asaad on April 15th, 2021
9. How to convert list of characters to a string in one line?
Technical interviewers often want to see if you can manipulate data. Sometimes there are built in methods that you can use however, sometimes it is beneficial to write the code and explain your thought process and procedure to show you have a deeper understanding of data types.
A list of characters can be converted in a string by using the string method called "join". This method, from its name, joins the elements of the list together as one element, a string. An example of that is in the code below :
chr_list = ['i ,'n' , 't' , 'e' , 'r' , 'v' , 'i' , 'e' , 'w' ]
string_ = "".join(chr_list)
Now, after joining each element in the "chr_list" list, the variable named "string_" is "interview".
This is an example of using a built in function.
Written by Aiad Asaad on April 15th, 2021
10. What is the definition of universal function in Python?
This interview question tests your knowledge of different definitions in Python.
Universal function (ufunc) uses ndarrays. ndarrays are objects that are arrays with fixed-sized elements. The universal function takes a fixed number of inputs and creates a fixed number of outputs.
Written by Aiad Asaad on April 15th, 2021
11. Write a python function to calculate the mean of a given list of integers.
Functions are an integral part of every programming language. In a technical interview it is important that you can demonstrate how to write a function that returns a desired output.
To write a python function, you must start the function body by the def statement to define and give the function a name. Naming functions accurately helps other developers understand your code. Interviewers are looking to see that you name all your functions appropriately.
Then, add the parameter you will pass to it in between two brackets. The parameter is essentially the input into the function.
Below is a python function to calculate the mean of a given list:
l=[1,2,3,4,5]
def Mean_of_list(a):
total=sum(a)
L=len(a)
Mean=total/L
return mean
The_Mean=Mean_of_list(l)
As you can see, I started the function by def followed by the function name stating the parameters inside the brackets.
In python, there is a built-in module named sum(), it takes a list and returns the sum of its integers. So, we first give the sum() of the given list and store them as the total sum of the integers inside the list (a).
After that, to determine the number of integers inside the list we can use the function len().
Finally, calculate the mean by dividing the total sum(total) by the number of integers(len).
Then, we must return the mean.
The return statement in any function will return the output after calling the function. To use the function you must call it and pass the given list to it as shown above in the code. To see the mean value of the list you should print the The_Mean variable.
Written by Aiad Asaad on April 15th, 2021
12. What do python modules mean?
Modules are an incredibly useful feature of python. We "import" modules and use the contents of the module in our code.
A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference.
Put simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code.
A module removes the requirement to rewrite functions previously created. This saves time and makes our code more readable.
Written by Aiad Asaad on April 15th, 2021
13. What is a negative index in Python?
This question tests the knowledge of accessing the indices in different ways.
In computer science the first index in a list is always 0. This is the same on python. The first element of a list is said to be at index 0.
We usually use the positive index to access a certain element in a list. So for example the second element of a list is at index 1 and so on.
Python accepts negative indexing as well, but it starts from right to left. For example, the last element of a list is at index -1 and the second last element of a list is at element -2.
This is a useful feature as it is very useful especially if you do not know the length of the left and want to see the last element.
If we have a list a = [1,2,3,4,9,5,3] and you need to access an element in the 4th index you can do that in two ways. The popular way is to use the positive index (3).
Another way is to use the negative index. So, you can access the last element in a list by the -1 index, and the one before the last by using index -2 and so on. Therefore, the 4th index using a negative index is (-len(list)+4-1)
An example of this in the following code:
If you have a list a=[4,2,6,8,2,4,4,5,6] and you want to see the element in index 2.
a=[4,2,6,8,2,4,4,5]
index_3_positive=a[3-1] # As the index started from 0
index_3_negative=a[-len(a)+3-1]
After running this code the two variables index_2_negative and index_2_positive will be the same with value 6.
Written by Aiad Asaad on April 15th, 2021
14. What are the pros and cons of Python being an interpreted language.
This is an example of a question that is targeted more at general computer science knowledge.
Pro:
Interpreted languages, such as Python, are platform-independent. This means that Python bytecode can be executed on any platform.
Interpreted languages are dynamically typed. This reduces the possibility of type errors.
Con:
Based on being independent of the platform, the interpreter has to do extra work to translate the bytecode in order for the code to be executed on the machine. This slows down the execution and makes Python slow.
For an analogy: Speaking to someone directly in their native language is quicker than having what you say translated into their native language for them to understand.
Written by Aiad Asaad on April 15th, 2021
15. What is the difference between Global and Local Variables?
It is important to know the "scope" of variables in any programming language. This question highlights the difference between a variable with a global scope and a variable with a local scope.
A Global variable is a variable defined outside of a function but we can use and access them within a function.
# This function uses global variable s
def f():
print(s)
# Global scope
s = "python question interview"
f()
The output will be "python question interview". The variable s is defined as the string "python question interview" before we call the function f(). The only statement in f() is the print (s) statement. As there are no locals, the value from the global will be used.
Local Variables are variables declared inside the function's body or in the local scope. This variable can only be used in this function and is not accessible by any other function as it is not a Global variable.
# This function has a local variable with
# name same as s.
def f():
s = "Hello"
print(s)
#Global scope
s = "python question interview"
f()
If a variable with the same name is defined inside the scope of the function, as well as in global, then it will print the value given inside the function only and not the global value.
#Imortant note:
def f():
print(s)
s = "Me too."
print(s)
# Global scope
s = "I love Geeksforgeeks"
f()
Very Important note:
The above code will show you an error. As the local variable s inside the function is referenced before assignment. To make the above program work, we need to use the “global†keyword.
We only need to use the global keyword in a function if we want to do assignments or change them. Global is not needed for printing and accessing. Why? Python “assumes†that we want a local variable due to the assignment to s inside of the f(). So, the first print statement throws this error message.
Any variable which is changed or created inside of a function is local if it hasn’t been declared as a global variable. To tell Python, that we want to use the global variable, we have to use the keyword “globalâ€, as can be seen in the following example:
def f():
global s
print(s)
s = "Look for Python Section"
print(s)
s = "Python is great!"
f()
Now the f() will print "Python is great!". Then this s will be changed inside the f() to be "Look for Python Section".
This is an example of how python treats Global and Local variables differently.
Written by Aiad Asaad on April 15th, 2021
16. What does "string data type is immutable" mean?
This interview question relates to understanding how data is stored and manipulated in Python. This is probably one of the most common questions in a python technical interview.
If it is immutable, it cannot be changed. So, if an item has already been assigned a value, this cannot be changed. It is immutable. For example, if you run this code to change the x[1] which is 'y' in 'python' to 'z':
x = 'python'
x[1]="z"
You will get an error: "TypeError: 'str' object does not support item assignment" because you are attempting to change an immutable string data type.
However, if you want to edit a string you can index and slice by creating another item and assigning the changes to that. For example:
y = x[0] + 'Z' + x[2:]
print(y)
The output will be pZthon. The y is assigned the value of the x[0] (first index item in x, which is p) and then sliced to change out the 'Z' for the 'y'. Then, the rest of the value is added from index item 2 along with the rest of the value assigned to x, which is 'thon'.
Note:
The x item assignment is not changed and if you run the code print(x), you will still receive the output of 'python'. The changes are only made to the y item.
To recap:
An immutable object cannot be changed. An example of an immutable data type in python is a Tuple. There are 4 data types in python: List, Set, Dictionary and Tuple.
Tuples are written with round brackets. For example: thistuple = ("Apple", "Orange", "Peach")
The tuple items are unordered and unchangeable. They do however allow for duplicate values.
Written by Aiad Asaad on April 15th, 2021
17. What is the difference between "remove" and "pop"?
This interview question tests the knowledge of the built-in methods in python. The interviewer wants to see if you are able to manipulate data with a data type.
The remove() function removes the first instance of a matching object. Below we remove the first b.
a = ['a', 'a', 'b', 'c', 'c']
a.remove('b')
If you print a, it will be a = ['a', 'a', 'c', 'c']
The pop() function removes an object by its index. The difference between pop and remove is that pop returns the popped element. This is an example of using a list like we would use a Stack.
a = ['a', 'a', 'b', 'c', 'c']
a.pop(2)
If you print a, it will be a=['a', 'a', 'c', 'c'].
We give pop() the index 2 as in python indices started from 0 so ['a' ->0, 'a'->1, 'b'->2, 'c', 'c'] .
Note:
By default, pop removes the last element from a list if an index isn’t specified.
Written by Aiad Asaad on April 15th, 2021
18. What is the time complexity of inserting, finding and deleting to or from a list?
This question tests the ability of writing code with the best complexity.
This is based on Big O Notation which is a method for determining how fast an algorithm is. There are two types of complexity:
1. Time Complexity
2. Computational or Space complexity
The worst case of the insertion is O(n). If an element is inserted at the beginning, all other elements must be shifted right. This takes time.
Finding by element using an index is O(n), elements need to be iterated over until the value is found. This takes more time as each item is gone over searching for the requested index.
The worst case of deletion is O(n). If an element is deleted at the beginning, all other elements must be shifted left.
Written by Aiad Asaad on April 15th, 2021
19. What is the difference between reverse and reversed?
This interview question tests the knowledge of the built-in methods in python. A built in method is a method that does not require the developer to import a library or module.
The reverse() method edits the list to be in a reversed order. However, reversed() method takes a list and returns an iterator of it in reverse order.
Below an example of how to use them:
L = [1,2,3,4,5,6,7,8,9,10]
L.reverse()
If you print L after running this code, it will be like this:
L=[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
L = [1,2,3,4,5,6,7,8,9,10]
a=reversed(L)
a=list(a)
If you print L after running this code it will be the same. However, if you print a, it will be [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]. The last line in the above code (a=list(a)) is to convert a to a list to be able to see all the elements of it.
As it is, before converting, an iterator which you cannot see all the elements inside it by the print statement.
Written by Aiad Asaad on April 15th, 2021
20. What is the difference between iterable and iterator in python?
This interview question tests the knowledge about the data type iterator in python.
An iterator is an object that stores a stream of data. It returns one element at a time.
It must have a built-in method called __next(). This method is used to return the next element in an iterator. Also, if there are no more next elements, it will return the StopIteration exception.
You can make an infinite iterator. Also, you cannot see the whole data inside the iterator by print. You can only iterate and print them element by element.
Iteretable is more generic. It is anything you can loop over with for loops such as lists, sets, tuples and iterators.
Therefore, we can say that any Iterator is iterable. However, not every iterable is an iterator.
For example, if we have a list containing integers we can iterate over that list using a for loop and print out each number. Therefore, the list is said to be iterable.
Written by Aiad Asaad on April 15th, 2021
21. How can you perform a deep copy of a list?
This answer shows the interviewer that the programmer is capable of copying Python objects without affecting the original.
In this example we "import" the "copy" library or module. This means we can use the functions already found in this library. We use the .deepcopy() function in this example.
deepcopy() preserves the graphical structure of the original. For example:
import copy
a1=[1,2,3,4]
a2=copy.deepcopy(a1)
print(a1, a2)
Here the output will be a1=[1,2,3,4] and a2=[1,2,3,4]
Also, deepcopy and the original are independent. So, if changes are made to one, it does not affect the other.
For simplicity, the deep copy is a built-in method that makes a new list in a new memory with the same original value as a given list.
Written by Aiad Asaad on April 15th, 2021
22. What does it mean that Python is Dynamically Typed Language?
This question is looking for an understanding of the Python language in general. There are two types of programming languages.
1. Dynamically Typed
2. Statically Typed
A Dynamically Typed Language means that you do not need to declare the type of the variable. For example, If you need to enter a variable x = 5, you will not need to first state that x is an integer variable. In Python, when the program runs, it assesses what type of variable it is based on what is assigned to it. This makes the code more readable.
In Statically Typed Languages, you must declare the type of variables before assignment. An example of a Statically Typed Language is C or C++. In C , an integer must be defined as follows:
int x = 5
Whereas in python we can just write:
x = 5
Written by Aiad Asaad on April 15th, 2021
23. State a simple way to create a stack in python.
This interview question focuses on simple data structures that can store and retrieve data sequentially or in order.
The stack is a data structure that stores elements, collections, names, and other data like a stack of blocks. After it is filled, the last element added is on the top of the stack and is the first element out, Last In First Out [LIFO].
The list can be used to create a stack using push() to add data to the top of the stack or pop() to remove the last data from the top of the stack.
One benefit of a stack is that elements can be added and removed in O(1) time (constant time) because the list does not need to be iterated over. The code simply grabs the last item in the stack.
An interviewer may ask the difference between LIFO and FIFO. LIFO stands for Last In First Out whereas FIFO stands for First In First Out.
Stacks are a great way to demonstrate your knowledge regarding "Big O" notation as well as showing that you can manipulate data structures.
Written by Aiad Asaad on April 15th, 2021
24. Write a code to extract all the unique letters for any given string.
This is a typical example of a technical python interview question. You should aim to outline your thought process as the interviewer is not only looking for the correct answer but for a detailed reasoning behind your process.
Communication skills are vitally important in a software development role. The interviewer wants to determine if you will be able effectively communicate with the development team and product managers. Often, people focus solely on the correctness of their code however you must also focus on guiding the interviewer through your process when arriving at the correct answer.
First, assign the string to a variable. Next, create an empty set to put the unique letters in. Next, create a for loop that will add unique letters to the set. We use the .add() method to add characters to the set.
The set then returns only the unique values unlike a list. This is an example where the selection of the correct data type is important as it removes unnecessary code from the answer.
A simple solution as in the code below.
s="HelloHi"
l={}
l=set(l)
for i in s:
l.add(i)
The output will be {'H', 'e', 'i', 'l', 'o'}.
You can write another code solution, but make sure the result contains unique letters. As an exercise to better understand data types, try and use a list as opposed to a set for this example and see how it increases the complexity and size of your code.
Written by Aiad Asaad on April 15th, 2021
25. What do you know about "Try Except " statement?
This interview question allows the programmer to show that they are able to handle exceptions in their coding.
This is a very important statement. It is used to handle an exception. For example to handle the zero division that is not permitted in Python.
An important usage is to ask the user to enter only an integer as the below code:
while True:
try:
x = int(input("Please enter a number: "))
break
except:
print("Oops! That was not a valid number. Try again...")
The code will only break if the user enters an integer.
It works as following:
The code will run then enter the block of try ask the user to enter a number then the int converts the number the user entered to an integer.
However, if the user enters a letter, for example, the code will exit from the try block and enter to the except block. Then the program will go back again from the first line in the while loop.
It will only break the while loop if the user enters a number. The break will make the program finish the while loop.
If you only write:
x=int(input("Please enter a number: "))
and the user enters a letter that cannot be converted to an integer, the program will show you an error.
Try Except statements can be used to check the validity of a users input. In an interview, you may be asked by the technical interviewer "What stops an user entering an incorrect input?". The Try Except statement is a good answer for this.
Written by Aiad Asaad on April 15th, 2021
26. Write a code to extract all the capital letters from a given string.
This answer shows that the programmer is capable of not only providing the correct end result but also their process of developing the solution.
It is often helpful to explain your logic and plan for writing the code before you begin this problem. It gives the interviewer an insight into your thought process and sometimes they can correct an invalid assumption you made before you go through the process of writing the code. This avoids you having to start the process of writing a solution over again.
You will need to create a loop for all letters in the string using the for loop. Before that, you will need to create a string with the capital letters assigned to a variable. A simple solution is shown in the code below:
s="Jack Fred Free AllAny BB"
capitals=[]
for i in s:
if i.isupper():
capitals.append(i)
In this code example we first define the variable "s" as the string "Jack Fred Free AllAny BB".
We then created an empty list called capitals. We will populate this list with our answers.
We then created a for loop. This loop iterates over each character in our string. In python, for loops are very user friendly compared with other programming languages.
We then used an if statement to check if the following condition is satisfied: isupper(). This method checks if the character is uppercase or not. If the character is uppercase it is added to the list called capitals via the .append() method.
The output of the code will be ['J', 'F', 'F', 'A', 'A', 'B', 'B'] which is what we are looking for.
Note:
You may write another simple solution but make sure the output contains all the capital letters
Written by Aiad Asaad on April 15th, 2021
27. What is special punctuation for control flows in python?
This interview question checks to see if the programmer understands how the code that they write is executed.
The control flows is how the program calls the statements in the right order. It tells the interpreter/compiler the beginning of a statement and its end.
Python uses indentation. It makes the code much more readable and the block hierarchy very clear. Each level is indented more than the one above or equal to those on the same level.
Note:
You should use a consistent definition of indentation through your work, especially in collaboration with others. The usual setting is 4 spaces but it can be another amount of spaces or just the tab character '\t'. Whatever you and your collaborators agree to stick to it and make sure the editors and IDEs you use adhere to it to avoid weird interpreter errors in big projects!
An example of a very well loved and widely used IDE (Integrated Development Environment) is Jupyter Notebooks. Jupyter Notebook not only acts as an IDE but as a presentation tool for data visualisation. It is very popular amongst data scientists.
Written by Aiad Asaad on April 15th, 2021
28. Why does Python have tuples AND lists? Aren't they the same thing?
This interview question relates to understanding different data types and their related rules in Python.
They are similar, but not the same. Their usage is almost identical, but modifying them is not. Tuples cannot be changed after their construction, while lists can. Also, the tuples are faster than lists.
Tuples are "immutable" whereas the list data type can be manipulated and changed.
You should choose the one you think is suitable according to what you want.
When you need to keep the stored items the same, the tuple would be the best choice. The Tuple removes any ambiguity relating to the data it stores. It makes it clear to others editing or refactoring your code that this data must remain unchanged throughout the program.
If you require a data type to store and change data throughout your code then a list is a more appropriate choice.
However, if neither of these options are important in your coding, the tuple is better because it is faster.
Written by Aiad Asaad on April 15th, 2021
29. What are the main three types of errors in python?
This interview question focuses on the programmer's awareness of python programming errors that they will run into most often. Debugging is a very important skill for a developer to have. Often more time is spent debugging a program or reviewing a coworkers errors than is spent writing new code.
The most important three types of errors any python programmer must know are the following:
1) Syntax errors:
- The mistake you made is in the structure of the code. For example, if you forget to close parentheses in a printing statement like this: print("I made an error). The compiler and/or interpreter will not even execute the program and send an error message "SyntaxError: invalid syntax"
2) Runtime Errors:
- It appears only when you run/execute the program. For example, if you divide by zero, the interpreter will run the code until the line dividing by zero, it will show you there is an error as the computer cannot interpret division by zero "ZeroDivisionError: division by zero". It is also called exceptional errors because they usually indicate that something exceptional (and bad) has happened.
3) Semantic Errors:
- This error only appears after the program runs successfully. However, it does not do the right thing. For example, you forget to divide by 100 to get the percentage of something. It is also considered the hardest error to find as you can not find the error quickly due to the fact that it is seen as a valid program but not providing the results the programmer wants.
In a technical interview you may be asked to debug a program. The best place to start is to run the program and make note of the errors returned. This will show the interviewer that you are efficient and have the ability to create a feedback loop in order to identify and attempt to fix the problem. Many first time interviewees, when presented with "buggy code" immediately attempt to go through each line. This may take a long time if the program has over 100 lines.
In the professional environment most developers start with the errors and work back from there in order to create a feedback loop and avoid searching for problems or mistakes in the wrong areas.
Written by Aiad Asaad on April 15th, 2021
30. What are the differences between the set and list data type?
This interview question relates to understanding different data types and their related rules in Python.
Lists are presented in [] (square brackets) and sets are placed within {} (curly brackets).
There are three main differences in rules regarding these two data types:
1) The list stores any value added to it. The set stores only the unique values.
For example, if you run this code:
x=[1,2,3,3,3]
y={1,2,3,3,3}
print(x,y)
The output will be x = [1,2,3,3,3] and y = {1,2,3}. No duplicates are printed from the values assigned to the set.
2) The list is mutable. The sets are immutable. That means we can change the items of a list by assignment, but we cannot do that with sets.
3) The lists are ordered. The sets are unordered. For example, if you have a list x=[3,4,1,9], the output will always be in that order and you will always have '4' as your second element. However, if you have a set y={3,4,1,9}, the order of the assigned values will be random and unknown.
Written by Aiad Asaad on April 15th, 2021