AlgoDaily

Python Interview Questions Cheat Sheet

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Introduction

Over the past few years, Python has gained popularity for its user-friendly nature and efficiency. If you've experienced other programming languages, you'll immediately appreciate its simple syntax and helpful characteristics.

The Python language is a legible and understandable one. This is what we mean by "user friendly" -- it reads almost like the English language. Even those who haven't programmed can comprehend what each line of code might do, and can take a guess of what is expected to happen upon execution.

Python isn't just limited to Windows (the operating system). It also works on operating systems like Linux, Solaris, macOS, etc. It's also an open-source language, so those who wish can fork it, add to it, or modify it to their heart's desire.

In terms of its applications, there are several. Because of its advanced features, it sees usage in fields like machine learning, AI, game development, website development, and many more. Additionally, it supports object-oriented programming (OOP), among other programming paradigms.

This tutorial aims to review the main concepts of Python that you need to ace your interview. So, without further ado-- let's get started with the interview questions.

0

Namespace Implementation

In Python, what data structure are namespaces implemented as?

Namespaces

What are namespaces in Python?

Before answering what namespaces are, let's quickly review some prior concepts. As you may remember, everything in Python is an object. Each object should have a unique name. For example, if you created a string for the word 'school':

place = "school"

The string "school" is an object whose name is place. This object is stored with a specific address that points to its location in memory.

The answer to the question "what are Python namespaces?" will be more intuitive with this background. You can think of them as containers that inhabit these objects along with their names. Interesting! Let's dive deeper.

When we execute our program, namespaces are created. The name of each object acts as a key and the object itself as a value. Every function, module, or library has its own unique namespaces. If we import the NumPy library, then upon execution of our program, the Python interpreter will generate NumPy's namespace.

0

True or False?

Every object in Python has a data type.

Basic supported types

List the basic supported data types

Computer Science is all about data-- exporting it, processing it, loading it, etc. Each piece of data has a type. For example, if we have a number, then its type is numeric. This identification is useful while programming to mentally categorize different objects.

Python supports multiple data types, and each has its own syntax and significance. The following are the main forms of data, and each is broken down into other types.

  • Numeric data
  • Text data
  • Boolean data

Let's dive into each one.

Note: In dynamically-typed languages like Python, we don't declare types explicitly. We create a variable and can immediately assign data to it. The interpreter then determines the intrinsic type. If you ever wanted to know the data type of an object, you can use type() function.

0

Numeric Data

Numeric Data

In Python, numeric information is represented by the following three data types:

  1. int - the data type int is for integers or the numbers that don't have the decimal point.

  2. float- the data type float is for numbers with decimal points.

  3. complex - the data type complex is for the numbers that contain an imaginary value. Let's implement one of each:

intVariable = 5
floatVariable = 4.5
complexVariable = complex(4, 3)

Now, if we want to check the types using the type() function:

print(type(intVariable))
print(type(floatVariable))
print(type(complexVariable))

The output will be:

<class 'int'>
<class 'float'>
<class 'complex'>
```python
import cmath 

intVariable = 5
floatVariable = 4.5
complexVariable = complex(4, 3)

print(type(intVariable))
print(type(floatVariable))
print(type(complexVariable))
```

Text Data

Text Data

The type string represents text data. Most text data contains alphabetical and alphanumeric information. Anything enclosed in ' ' or " " is a string. It can be any number, word, sentence, or special character. Let's see it in action:

string1 = "Minahil"
string2 = 'Minahil123'
string3 = 'Min@hi!'

Now, if we check the data types using type() function:

print(type(string1))
print(type(string2))
print(type(string3))

The output will be:

<class 'str'>
<class 'str'>
<class 'str'>
```python
string1 = "Minahil"
string2 = 'Minahil123'
string3 = 'Min@hi!'

print(type(string1))
print(type(string2))
print(type(string3))
```

Type Buckets

Python values are easiest to remember as small buckets: numbers, text, and truth values.

Notice that the variable name is not the type. The object on the right side of the assignment has the type, and Python connects the name to that object.

Type Buckets

Python Type Map

Before we add booleans, pause and organize the core idea: every Python value has a type, and that type tells Python which operations make sense.

Use this visual as a quick mental map. Notice that 5, 4.5, and '5' may look related, but Python treats them as different objects because their types are different.

Python Type Map

Boolean Data

Boolean Data

In Python, boolean data has either a True or False value. For example,

data = True
data1 = False

Now, if we check the data types using type() function:

print(type(data))
print(type(data1))

The output will be:

<class 'bool'>
<class 'bool'>
```python
data = True
data1 = False

print(type(data))
print(type(data1))
```

Step Nine

To execute a function, we need to ______ that function.

What Are The Most Commonly Used Built In Functions In Python?

What are the most commonly used built-in functions in Python?

The commonly used built-in functions in Python are:

  • print()
  • len()
  • min()
  • max()
  • type()
  • isinstance()

The details of these functions are given below:

Function Description print() It is used to display anything on the console. len() It is used to find the length of a string, list, tuple, dictionary, etc. min() It is used to find the minimum value out of multiple values. max() It is used to find the maximum value out of multiple values. type() It tells about the data type of a variable. isinstance() It confirms if a variable is of xyz type. For example, if 5 is int? This function returns True if yes.

Let's try out each function for a better understanding.

0

Len()

len()

We can find the length of a string, list, tuple, and a dictionary using the len() function. Let's create one of each and find their lengths.

string = "Minahil"
Flowers_List = ["Tulip", "Jasmine", "Rose", "Lili", "Daisy"]
Number_Tuple = ("one", "two", "three")
General_Dictionary = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
    "key4": "value4",
}

Now, we will find the length using len() function.

print("The length of string is", len(string))
print("The length of list is", len(Flowers_List))
print("The length of tuple is", len(Number_Tuple))
print("The length of dictionary is", len(General_Dictionary))

The output will be:

The length of string is 7
The length of list is 5
The length of tuple is 3
The length of dictionary is 4
```py
string = "Minahil"
Flowers_List = ["Tulip", "Jasmine", "Rose", "Lili", "Daisy"]
Number_Tuple = ("one", "two", "three")
General_Dictionary = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
    "key4": "value4",
}

print("The length of string is", len(string))
print("The length of list is", len(Flowers_List))
print("The length of tuple is", len(Number_Tuple))
print("The length of dictionary is", len(General_Dictionary))
```

Built In Function Flow

Most built-ins follow the same mental model: pass a value in, get a result back.

For interviews, focus less on memorizing examples and more on knowing what each function returns: print() displays, while len() returns a count.

Built In Function Flow

Built-ins At A Glance

These built-ins are interview staples because they answer common questions quickly: display it, measure it, inspect it, or compare it.

In the visual, focus on the pattern: a function takes an input object, performs one small job, and returns or prints a result.

Built-ins At A Glance

Min()

min()

The min() function finds the minimum value of a string, list, tuple, dictionary or multiple values passed as a parameter. Let's find the minimum values of the string, list, tuple and dictionary created prior.

print("The minimum value of string is", min(string))
print("The minimum value of list is", min(Flowers_List))
print("The minimum value of tuple is", min(Number_Tuple))
print("The minimum value of dictionary is", min(General_Dictionary))

The output will be:

The minimum value of string is M
The minimum value of list is Daisy
The minimum value of tuple is one
The minimum value of dictionary is key1

Now if we pass multiple values in min() function as parameter, let's see what happens

min(1, 4, -5, 6, -10, 0)

The output will be:

-10
```py
string = "Minahil"
Flowers_List = ["Tulip", "Jasmine", "Rose", "Lili", "Daisy"]
Number_Tuple = ("one", "two", "three")
General_Dictionary = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
    "key4": "value4",
}


print("The minimum value of string is", min(string))
print("The minimum value of list is", min(Flowers_List))
print("The minimum value of tuple is", min(Number_Tuple))
print("The minimum value of dictionary is", min(General_Dictionary))
```

Max()

max()

The max() function finds the maximum value of a string, list, tuple, dictionary, or of multiple values passed to it as parameters. Let's find the maximum values using the string, list, tuple and dictionary created before.

print("The maximum value of string is", max(string))
print("The maximum value of list is", max(Flowers_List))
print("The maximum value of tuple is", max(Number_Tuple))
print("The maximum value of dictionary is", max(General_Dictionary))

The output will be:

The maximum value of string is n
The maximum value of list is Tulip
The maximum value of tuple is two
The maximum value of dictionary is key4

Now if we pass multiple values in max() function as parameter, let's see what happens

max(1,4,-5,6,-10,0)

The output will be:

6
```py
string = "Minahil"
Flowers_List = ["Tulip", "Jasmine", "Rose", "Lili", "Daisy"]
Number_Tuple = ("one", "two", "three")
General_Dictionary = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
    "key4": "value4",
}


print("The maximum value of string is", max(string))
print("The maximum value of list is", max(Flowers_List))
print("The maximum value of tuple is", max(Number_Tuple))
print("The maximum value of dictionary is", max(General_Dictionary))
```

Min Max Comparison

min() and max() do not magically know what you "mean" by smallest or largest. They use Python's ordering rules for the values you give them.

For numbers, that usually feels obvious. For strings and dictionary keys, think lexicographic ordering: Python compares characters in sorted order.

Min Max Comparison

Min Max Ordering

min() and max() are simple when the inputs are numbers. With strings, lists of strings, tuples, or dictionary keys, Python still compares values using an ordering rule.

The key interview takeaway: these functions do not "understand meaning" — they select the smallest or largest item according to Python's comparison order.

Min Max Ordering

Type()

type()

We will create the variables of multiple types and check their types using the type function.

var1 = 5
var2 = "Minahil"
var3 = True
var4 = 0.6
var5 = 4j

Using the type() function:

print(type(var1))
print(type(var2))
print(type(var3))
print(type(var4))
print(type(var5))

The output will be:

<class 'int'>
<class 'str'>
<class 'bool'>
<class 'float'>
<class 'complex'>
```py
var1 = 5
var2 = "Minahil"
var3 = True
var4 = 0.6
var5 = 4j

print(type(var1))
print(type(var2))
print(type(var3))
print(type(var4))
print(type(var5))
```

Isinstance()

isinstance()

The function isinstance() accepts two parameters. One is a value and the other is a data type. It then checks if the value passed is of the given data type. Let's see how it works.

print(isinstance(6, int))
print(isinstance(6, str))
print(isinstance(3j, complex))

The output will be:

True
False
True
```py
print(isinstance(6, int))
print(isinstance(6, str))
print(isinstance(complex(1, 2), complex))
```

What Are Dict And List Comprehensions?

A list comprehension is more efficient in performance than a loop.

What Are Dict And List Comprehensions?

What are Dict and List Comprehensions?

The comprehensions in Python are simple ways to create a new object from an existing object. There are several of these, including list, dict, set, and nested comprehensions. Let's focus on dict and list comprehensions.

We know that a dictionary is used to store sorted data. It utilizes keys and values (instead of indices and values like a list). Similar to how we have a specific index for a value in a list, we'll have a specific key for each value in the dictionary.

first_dictionary = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
    "key4": "value4",
}

The above dictionary contains four keys and four values. A key can be any number or string, and should be unique. The syntax of dict comprehension is:

dict_name = {key: value for (key, value) in oldDict.items()}

Now, we will create a new dictionary from first_dictionary. We won't create a duplicate dictionary, but we'll add some values to its existing value.

new_dictionary = {key: value + " new" for (key, value) in first_dictionary.items()}

This will generate the following dictionary:

{"key1": "value1 new", "key2": "value2 new", "key3": "value3 new", "key4": "value4 new"}

We can accomplish this task using a loop, but it's more expensive. We can also pass any condition into comprehensions.

0

List Comprehensions

List Comprehensions

A list comprehension has the same functionality as dict comprehensions, but is for lists. A list has a specific index for each value. For example, look at the following list of flowers:

flowers = ["Tulip", "Jasmine", "Rose", "Lili", "Daisy"]

If you wanted to create a new list that contains new flowers, you could use a comprehension instead of a loop. The list comprehension has the following syntax:

list_name = [expression for variable in old_list condition]

Let's create a new list using the flowers one:

new_flowers = ["new" + flower for flower in flowers]

The output will be a new list as follows:

["newTulip", "newJasmine", "newRose", "newLili", "newDaisy"]
```py
flowers = ["Tulip", "Jasmine", "Rose", "Lili", "Daisy"]

new_flowers = ["new" + flower for flower in flowers]

print(new_flowers)
```

Operators Other Than Arithmetic/Logical

The object on which an operator is invoked against is called an ____________.

Comparison Operators

Are there operators in Python other than arithmetic and logical operators?

Yes, there are operators in Python other than arithmetic and logical ones. The others are comparison, identity, membership, and assignment operators. Each type of operators contains multiple operators. Let's have a look at each one by one.

Comparison Operators

These operators are used for the comparison between two values. These are following:

Operator How to use Function == value1 == value2 Checks if value1 is equal to value2 > value1 > value2 Checks if value1 is greater than value2 < value1 < value2 Checks if value1 is less than value2 >= value1 >= value2 Checks if value1 is greater than and equal to value2 <= value1 <= value2 Checks if value1 is less than and equal to value2 <> value1 <> value2 Checks if value1 is not equal to value2 != value1 != value2 Checks if value1 is not equal to value2
Identity Operators

These operators are used to compare the identity of the variables or type of the variables.

Operators How to use Function is value1 is value2 Checks if both the objects refer to the same object is not value1 is not value2 Checks if both the objects do not refer to the same object
Membership Operators

These operators are used to check the membership of a variable in a sequence like lists, strings, etc.

Operators How to use Function in value1 in anySequence If used with a condition, it checks if a value is present in a sequence. If used with a for loop, it creates value1 variable and assign sequence values to it one by one. not in value1 not in anySequence If used with a condition, it checks if a value is not present in a sequence.
Assignment Operators

These operators are used to assign a value to a variable. The main assignment operator is =. It can be used with the arithmetic operators.

Operators How to use Function = value1 = value2 It updates the value of value1 and assigns value2 to it. += value1 += value2 It adds the value1 and value2 and assigns the new value to value1 -= value1 -= value2 It subtracts value2 from value1 and assigns the new value to value1 *= value1 *= value2 It multiplies value1 and value2 and assigns the new value to value1 /= value1 /= value2 It divides value1 by value2 and assigns the new value to value1 %= value1 %= value2 It takes the modulus of value1 and value2 and assigns the new value to value1
0

Multiple Choice

Which of the functions are the part of the iterator protocol?

Iterators and Their Importance

Explain the use of iterators and their importance

An iterator is an object that can be "traversed" through. In other words, it is an object that can be accessed in iterations in place of the full object.

In Python, an iterator is any object that implements the iterator protocol. The protocol contains two built-in functions (iter() and next()). A list is a built-in iterator in python. However, to invoke next(), we would still need to convert it to an iterator object using the iter() method.

newList = [1, 2, 3, 4, 5]
next(newList)

The output will be the following error:

This is because it is not fully implementing the iterator protocol.

newList = [1, 2, 3, 4, 5]
object = iter(newList)
next(object)

Now that it's fully implementing the protocol, our output will be:

1
```py
# newList = [1, 2, 3, 4, 5]
# next(newList)

newList = [1, 2, 3, 4, 5]
object = iter(newList)
next(object)
```

What Are Generators?

A generator is a function.

What Are Generators?

What are generators?

A generator is a function used to create iterator objects. it returns an object that can only be used with the for-in loop or next() methods.

But how does the compiler know that something is a generator? There's a special keyword yield for them. Whenever you see a yield keyword inside a function, we know that it is a generator.

Now let's see how a generator works. We can create a simple one:

def simpleGenerator():
    yield "a"
    yield "b"
    yield "c"
    yield "d"

Now, if we call this function, it will return an iterator object.

object = simpleGenerator()

If we try to access this object by using the print() function, it will generate the following output:

print(object)

The output is:

<generator object simpleGenerator at 0x0000017884AF2AC8>

We can only access this object using a for-in loop or the next() function.

for value in simpleGenerator():
    print(value)

The output will be our iterator object:

a
b
c
d

We can now use next() function, but it won't display the entire object. For example, look at the following code and its output:

object = simpleGenerator()
next(object)

The output will be:

'a'

It has only shown the first yield value.

```python
def simpleGenerator():
    yield "a"
    yield "b"
    yield "c"
    yield "d"
    
object = simpleGenerator()

print(object)

for value in simpleGenerator():
    print(value)
```

Step Twenty Six

Object Oriented Programming leans on the idea of classes and ________.

OOP

What are the main features of OOP when used in Python?

Object Oriented Programming (OOP) in Python isn't much different than in other languages. It has the same major ideas with a different syntax.

We still use the following big concepts:

  • Classes and objects
  • Inheritance
  • Encapsulation
  • Polymorphism
  • Abstraction

The above mentioned are the main ideas of traditional OOP as well. A class in Python is defined using the keyword class. Similarly, objects are the instances of a class.

0

Other OOP Concepts

Inheritance in OOP is similar to genetic inheritance in real life. The classes assume or take over characteristics from a parent class. We have four types of this in Python:

  1. Single inheritance
  2. Multiple inheritance
  3. Multilevel inheritance
  4. Hierarchical inheritance

The figure below will give you a basic idea of each type.

Encapsulation is a process in which we enclose our values. We gather all the data and methods at one place.

Polymorphism is a process that defines multiple ways to perform a single action. It is a property of the object that allows it to take multiple forms. There are two types of polymorphism in Python:

  1. Run-time polymorphism
  2. Compile-time polymorphism

Abstraction is a when we hide system details or complexities from end users. When we create an abstract class, it can't have any objects. This class just provides functions for other classes to inherit.

0

True or False?

A decorator can be added inside a function.

Decorators

What is a decorator in Python?

Python offers a unique feature called decorators.

Let's start with an analogy before getting to the technical definition of the decorators. When we mention the word "decorator", what enters your mind? Well, likely something that adds beauty to an existing object. An example is when we hang a picture frame to a wall to enhance the room.

Decorators in Python add some feature or functionality to an existing function without altering it.

Let's say we have the following simple function that takes two numbers as parameters and divides them.

def divide(first, second):
    print ("The result is:", first/second)

Now if we call this function by passing the two values 16 and 4, it will return the following output:

divide(16, 4)

The output is:

The result is: 4.0
```py
def divide(first, second):
    print ("The result is:", first/second)

print(divide(16, 4))
```

Step Thirty One

What will happen if we pass the number 4 first, and 16 after? The answer will be 0.25. But we don't want it to happen. We want a scenario where if we see that first < second, we swap the numbers and divide them. But we aren't allowed to change the function.

Let's create a decorator that will take the function as a parameter. This decorator will add the swipe functionality to our function.

def swipe_decorator(func):
    def swipe(first, second):
        if first < second:
            first, second = second, first
        return func(first, second)

    return swipe

Now we have generated a decorator for the divide() function. Let's see how it works.

divide = swipe_decorator(divide)
divide(4, 16)

The output is:

The result is: 4.0

We have passed the function as a parameter to the decorator. The decorator "swiped our values" and returned the function with swiped values. After that, we invoked the returned function to generate the output as expected.

```py
def divide(first, second):
    print ("The result is:", first/second)

def swipe_decorator(func):
    def swipe(first, second):
        if first < second:
            first, second = second, first
        return func(first, second)

    return swipe


divide = swipe_decorator(divide)
divide(4, 16)
```

Data Structures

What are Data Structures in Python?

Data structures are the fundamental constructs around which you build your programs. Let's look at the 4 most common types, List,Tuple,Set and Dictionary.

We can compare these structure on the following five characteristics: - Mutable: We can change, add , and remove items in the structure after it has been created. - Ordered: The items in the structure have a defined order that will not change. If you add new items they will be placed at the end of the structure. - Duplicates: Allows items with the same value. - Different Objects: Allows objects of different data types.

When Should I use a Dictionary as a Data Structure?

As we seen from before a Dictionary is a structure that stores key-value pairs. We would use this structure in the following scenarios:

  • Quick access to a data point (value), since the data points are uniquely associated with labels (key)
  • When the order of the data points is irrelevant.
How is Memory Stored and Retrieved in a Python Dictionary?

Python's Dictionary is implemented using hash tables. This table is made up of three parts: - Hash ID - Keys - Values

Because of this concept, Python's dictionary is a useful data structure for quickly retrieving relevant value by calling the key. Let's consider the following Python dictionary example where the key is the piece of clothing, and the value is the price:

clothes_price = {'dress':29.99, 'shoes':19.99, 'shirt': 19.99, 'shorts':14.99}

clothes_price['dress']

By using the square bracket, we can retrieve the value of a specific key giving the following output:

29.99
When Sorting a List What is the Difference Between sorted() and .sort()?

To see the difference, let's illustrate with an example.

# Our list
my_list = [2,9,1,6,2,5]
  • sorted
sort_method_1 = sorted(my_list)
print('Sorted List 1: ', sort_method_1, 'Old List: ', my_list)

We get the following output:

Sorted List:  [1, 2, 2, 5, 6, 9] Old List:  [2, 9, 1, 6, 2, 5]
  • .sort()
sort_method_2 = sort_example.sort()
print('Sorted List 2: ', sort_method_2, 'Old List: ', my_list)

We get the following output:

Sorted List 2:  None Old List:  [1, 2, 2, 5, 6, 9]

As demonstrated above sorted() creates another list that is sorted whereas .sort() changes our original list my_list instead of creating another.

Multiple Choice

Which one of the following data structures is immutable?

Slicing

What is Slicing?

Is the way to access a part of a List, String, or Tuple.

We use ObjectName[start:stop:step] to slice where: - Start: specifies the starting element of a slice (included) - Stop: specifies the ending element of a slice (not included) - Step: (optional) specifies the increment between each index for slicing, default to one if not provided

Let's demonstrate with a list: ```python

Our list

my_list = ['Carl Cox', 'Fred again..', 'Sonny Fodera', 'MK', 'Denis Sulta','Boots & Kats'] ```

  • Positive Slicing
my_list[1:4:1] # can also be written as my_list[1:4]

Let's add a step size.

my_listmy_list[0:5:2]

  • Negative Slicing
my_list[-1:-4:-1]

Again, let's add a step size.

my_list[-1:-6:-3]

True or False?

The Stop index is inclusive in slicing.

Coding Questions

Sample Glassdoor Python Interview Questions

Now let's look at some questions based off Python Interview Questions from Glassdoor.

Level: Easy

After the success of Black Friday in the Cosmetics department at El Corte Inglés you've been asked to see what employee had the highest sales.

The dataset below is given, with employees by department and their sales. Find the Employee's ID, name and sales.

import pandas as pd
import numpy as np

# Filter to Cosmetics Department
cosmetic_department = department_sales[department_sales['department'] == 'Cosmetics']

# Create a rank
cosmetic_department['rank'] = cosmetic_department['sales'].rank(method='min', ascending=False)
top_employee = cosmetic_department[cosmetic_department['rank'] == 1][['emp_id','first_name','sales']]

top_employee

So, congratulations to John who'll be receiving a bonus reward for his efforts.

Level: Medium

The team at El Corte Inglés now want to find the employee with the lowest sales over Black Friday, and where they are based so HR can assess their overall capacity for the role.

You've been given an additional dataset, which refers back to the previously given dataset. Find the Employee's ID, name and sales.

import pandas as pd
import numpy as np

# Merge the datasets
merged_df =  pd.merge(department_sales, emp_location, on='emp_id')

# Find the minimum value
min_sales = merged_df[merged_df['sales'] == merged_df['sales'].min()][['emp_id','first_name','emp_store']]

min_sales

Level: Hard

The team at Zara are reviewing their customers' transactions, and you have been tasked with locating the customer who has the third highest total transaction amount.

You've been given two datasets, with information on customers called customers and card_orders with information on card orders placed. Find the Customers ID, and total purchases.

import pandas as pd
# Merge the datasets
merged = pd.merge(
        customers, card_orders, left_on="id", right_on="cust_id", how="inner")

# Get total purchases by customer id
merged = merged.groupby(["cust_id"])["total_order_cost"].sum().to_frame('total')

# Use rank function to get third customer
merged["rank"] = merged["total"].rank(method='dense', ascending=False)
result = merged[merged["rank"] == 3]
result

As you can see in this question we have a tie for third place, hence we use a .rank() function. If we used the .head() our answer would have been only half correct.

One Pager Cheat Sheet

One Pager Cheat Sheet

  • Python is an easy-to-read, open-source language that works on many operating systems, and has multiple applications ranging from website development to machine learning.
  • Namespaces in Python are implemented as dictionaries, providing an efficient data structure for mapping variables and their values to ensure no naming collisions occur.
  • Namespaces in Python are containers that hold objects and their names as keys and values respectively, with each function, module, or library having its own unique namespace.
  • Objects in Python have specific data types which determine what kinds of information they store and how they behave when used or manipulated.
  • Python offers a wide variety of data types to handle data, including numeric, text, and Boolean.
  • Python int, float, and complex data types are used to represent numeric information.
  • Strings, defined using ' ' or " ", are a type of text data that can include any number, word, sentence, or special character.
  • Python names point to typed objects like int, float, complex, str, and bool.
  • Python values are objects with types; similar-looking values can behave differently because their types differ.
  • In Python, boolean data is of class 'bool' and has either a True or False value.
  • We need to invoke or call a function to execute it, which is usually represented by the function's name followed by parenthesis ().
  • The most commonly used built-in functions in Python are print(), len(), min(), max(), type(), and isinstance().
  • The print() function can be used to output strings, variables, and even literal values like integers and booleans.
  • We can use the len() function to find the length of a string, list, tuple, and dictionary.
  • A built-in function takes input, performs one focused operation, and either displays or returns a result.
  • Common built-ins are small tools: print() displays, len() measures, type() inspects, and min()/max() compare.
  • The min() function finds the minimum value of a string, list, tuple, dictionary or multiple values passed as a parameter, resulting in -10 when multiple values are passed.
  • The max() function finds the maximum value of a string, list, tuple, dictionary, or of multiple values passed to it as parameters.
  • min() and max() return the lowest or highest item according to Python's comparison order.
  • min() and max() choose values by Python's ordering rules, not by human meaning.
  • We can create different variables and check their types using the type() function.
  • The isinstance() function checks if a given value is of a specific data type.
  • List comprehensions are an efficient and effective way to loop and filter through data, requiring fewer lines of code and often being more computationally efficient.
  • Dict and List Comprehensions are concise ways of creating new objects from existing ones, utilizing keys and values for dictionaries and indices and values for lists.
  • List Comprehensions allow for quickly creating a new list from an existing one using the expression for each variable within the list that meets certain conditions.
  • An operand is the object that an operator is applied to.
  • Yes, Python has multiple types of operators such as comparison, identity, membership, and assignment which can be used for different purposes.
  • An object is iterable when it implements the iterator protocol which consists of the iter() and next() methods for initializing the iterator and calling the next item, respectively, and raising the StopIteration exception when the final item is reached.
  • Iterators encapsulate the iteration process and are essential to accessing objects in Python.
  • Yes, a generator is a function that returns an iterator and can yield a sequence of values without storing them in memory.
  • A generator is a special type of function marked by the yield keyword, which returns an iterator object that can only be used with the for-in loop or next() methods.
  • Object Oriented Programming (OOP) relies heavily on classes and objects, which serve as blueprints that describe the attributes, behaviors, and construction of a real-life object that can be created and have its methods and attributes accessed.
  • OOP in Python utilizes traditional concepts such as classes, objects, inheritance, encapsulation, polymorphism, and abstraction, just with a different syntax.
  • Inheritance, Encapsulation, Polymorphism, and Abstraction are all key principles of Object Oriented Programming that allow developers to create organized, extensible, and powerful software.
  • Decorators can be used to add functionality to a function by being wrapped around it.
  • Decorators in Python can be used to add some feature or functionality to an existing function without altering it, like hanging a picture frame to enhance a room.
  • We have used a swipe_decorator() to add the functionality to our divide() function so that it swaps the values before they get divided if first < second.
  • Data Structures in Python are Mutable, Ordered, allow for Duplicates and Different Objects and can be used for quickly retrieving relevant data with unique labels by using a Dictionary, and the difference between sorted() and .sort() is that sorted() creates another list that is sorted whereas .sort() changes our original list.
  • A Tuple is an immutable data structure that does not allow for changes to be made after it is created.
  • Slicing is a way of programatically accessing parts of Lists, Strings, and Tuples by using ObjectName[start:stop:step].
  • In slicing, the Stop index is not inclusive of the element at the specified index, which can be demonstrated by looking at the result of my_list[1:4] and my_list[-1:-4:-1].
  • This article explores the use of Python (with import pandas and numpy) to solve Glassdoor interview questions related to aggregating data and working with datasets.
Open interactive view →