Python
What does “__init__” do in Python?
The __init__
function is a constructor in Python. The __init__.py file makes Python treat the containing folder as a Python package.
What does dynamically typed language mean in Python?
A dynamically typed language is a language where there is no need to declare a variable type on an assignment. Python is a dynamically typed language which means that for example, x = 0
does not need a type declaration because the Python interpreter automatically assumes x is an integer.
What does the “with” keyword do in Python?
The with
keyword is a statement used to make exception handling cleaner and simpler.
# using with statement
with open('myfile.txt', 'w') as file:
file.write('DataCamp Black Friday Sale!!!')
The above handles try, finally, and close on a single statement.
What is “list comprehension” in Python and what does it do?
List comprehension offers a shorter syntax to create a list based on the values of an existing list. For example:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
This can be achieved using list comprehension using the following syntax:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
What is the “map” function in Python and what does it do?
The map function returns an iterator after applying a function to an iterable object.
# Return double of n
def addition(n):
return n + n
# We double all numbers using map()
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
What does the “get” function do on a Python dictionary?
The get
function in Python returns a value from the list by key name, optionally allowing for a default value to be returned if the key does not exist.
dictionary.get(keyname, value)