Q151 - 300 Flashcards

(35 cards)

1
Q

151 What does filter() function do and what is its syntax?

A

The filter() function filters the given sequence with the help of a function that tests each element in the sequence to be true or not.

syntax: filter (function, iterable)

example:

L = [1,2,3,3,5,4,7,8,9]

L1 = list(filter(lambda x: x%2 == 0, L))

print(L1)

[2, 4, 8]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

152 What is a list comprehension and what is its syntax?

A

List comprehensions are a concise way to create lists from other lists using mapping and filtering in one line of code.

syntax:

[for in if]

only mapping:

things = [2, 5, 9]

yourlist = [value * 2 for value in things]

print(yourlist)

[4, 10, 18]

only filtering:

def keep\_evens(nums):
 new\_list = **[num for num in nums if num % 2 == 0]**
 return new\_list

print(keep_evens([3, 4, 6, 7, 0, 1]))

[4, 6, 0]

both:

things = [3, 4, 6, 7, 0, 1]
#chaining together filter and map:
print(map(lambda x: x\*2, filter(lambda y: y % 2 == 0, things)))

equivalent version using list comprehension
print([x*2 for x in things if x % 2 == 0])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

153 What’s the syntax for retrieving all the names of testers from the following nested dictionary using list comprehension?

tester = {‘info’: [{“name”: “Lauren”, ‘class standing’: ‘Junior’, ‘major’: “Information Science”},{‘name’: ‘Ayo’, ‘class standing’: “Bachelor’s”, ‘major’: ‘Information Science’}, {‘name’: ‘Kathryn’, ‘class standing’: ‘Senior’, ‘major’: ‘Sociology’}, {‘name’: ‘Nick’, ‘class standing’: ‘Junior’, ‘major’: ‘Computer Science’}, {‘name’: ‘Gladys’, ‘class standing’: ‘Sophomore’, ‘major’: ‘History’}, {‘name’: ‘Adam’, ‘major’: ‘Violin Performance’, ‘class standing’: ‘Senior’}]}

A

list_compri = [person[‘name’] for person in tester[‘info’]]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

154 What does zip() function do and what is its syntax?

A

It takes two or more iterators and returns a zip object, which is an iterator of tuples, where items of the same index are put together in a tuple.

If the passed iterators are of different length, the new object has the length of the shortest one.

syntax:

zip(iterator1, iterator2, iterator3 …)

example:

fruits = ['apple', 'pear', 'plum', 'banana']
prices = [10, 15, 20]

print(list(zip(fruits,prices)))

[(‘apple’, 10), (‘pear’, 15), (‘plum’, 20)]

new_dict = {fruits: prices for fruits,prices in zip(fruits, prices)}

print(new_dict)

{‘apple’: 10, ‘pear’: 15, ‘plum’: 20}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

155 What does sum() function do and what is its syntax?

A

It sums up the numbers in a list with an optional start parameter that is added to the final sum. If not provided it is assumed to be zero.

syntax: sum (iterable, start)

example:

L = [1,2,3]

print(sum(L))
print(sum(L,4))

6
10

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

156 How can we flatten a list of lists (put all elements into one list) using list comprehension?

A

By using a list comprehension with two loops:

top_list = [[“hi”, “bye”], [“hello”, “goodbye”], [“hola”, “adios”, “bonjour”, “au revoir”]]

flat_list = [item for sub_list in top_list for item in sub_list]

print(flat_list)

[‘hi’, ‘bye’, ‘hello’, ‘goodbye’, ‘hola’, ‘adios’, ‘bonjour’, ‘au revoir’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

157 How can we modify all elements of list of lists and put them into one list?

A

By using a list comprehension with two loops:

top_list = [[1,2], [3,4], [5,6,7,8,9]]

modified_list = [num+1forsub_listintop_listfornuminsub_list]

print(modified_list)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

158 How can we modify each element of list of lists and keep them in sub-lists?

A

By using two nested list comprehension statements, one to create the outer list of lists, and one to create the inner lists.

The main idea is to use a list comprehension statement by itself as “expression” of the outer list comprehension statement . We can create any object we want in the expression part of our list comprehension statement:

top_list = [[1,2], [3,4], [5,6,7,8,9]]

modified_list = [[num+1fornuminsub_list]forsub_listintop_list]

print(modified_list)

[[2, 3], [4, 5], [6, 7, 8, 9, 10]]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

159 How do we find all possible pairs of users from a list of them?

A

By using a list comprehension:

users = [“John”, “Alice”, “Ann”, “Zach”]

pairs = [(x,y) for x in users for y in users if x!=y]

print(pairs)

[(‘John’, ‘Alice’), (‘John’, ‘Ann’), (‘John’, ‘Zach’), (‘Alice’, ‘John’), (‘Alice’, ‘Ann’), (‘Alice’, ‘Zach’), (‘Ann’, ‘John’), (‘Ann’, ‘Alice’), (‘Ann’, ‘Zach’), (‘Zach’, ‘John’), (‘Zach’, ‘Alice’), (‘Zach’, ‘Ann’)]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

160 How do we create a nested list with list comprehension? How do we change the number of nested levels?

A

By using brackets:

lst1 = [[x,y,z] for x in range(2) for y in range(2) for z in range(2)]

print(lst1)

[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]

lst2 = [[[x,y,z] for x in range(2)] for y in range(2) for z in range(2)]

print(lst2)

[[[0, 0, 0], [1, 0, 0]], [[0, 0, 1], [1, 0, 1]], [[0, 1, 0], [1, 1, 0]], [[0, 1, 1], [1, 1, 1]]]

lst3 = [[[[x,y,z] for x in range(2)] for y in range(2)] for z in range(2)]

print(lst3)

[[[[0, 0, 0], [1, 0, 0]], [[0, 1, 0], [1, 1, 0]]], [[[0, 0, 1], [1, 0, 1]], [[0, 1, 1], [1, 1, 1]]]]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

161 What is “if __name__ == ‘__main__’:” expression used for?

A

It is used to execute some code only if the file was run directly, and not imported.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

162 What does strftime() function do?

A

It is used to convert date and time objects to their string representation. It takes one or more input of formatted code and returns the string representation.

syntax:

from datetime import datetime as dt

date_now = dt.now()

str_date = date_now.strftime(“%Y-%b-%d %H:%M:%S”)

format overview:

https://strftime.org/

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

163 Which of I, II, and III below gives the same result as the following nested if?

# nested if-else statement

x = -10

if x < 0: print(“The negative number “, x, “ is not valid here.”)

else:

if x > 0:

print(x, “ is a positive number”) else:

print(x, “ is 0”)

I.

if x < 0: print(“The negative number “, x, “ is not valid here.”)

else x > 0: print(x, “ is a positive number”)

else: print(x, “ is 0”)

II.

if x < 0: print(“The negative number “, x, “ is not valid here.”)

elif x > 0: print(x, “ is a positive number”)

else: print(x, “ is 0”)

III.

if x < 0: print(“The negative number “, x, “ is not valid here.”)

if x > 0: print(x, “ is a positive number”)

else: print(x, “ is 0”)

A

only II.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

164 What is the output from the following code?

a = 3

b = (a != 3)

print(b)

A

False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

165 What are the alternative operators for operations with sest?

A

first_set.union(second_set) = first_set | second_set

first_set.intersection(second_set) = first_set & second_set

first_set.difference(second_set) = first_set - second_set

(and the opposite)

first_set.symmetric_difference(second_set) = first_set ^ second_set

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

166 How to modify a set with operations (instead of creating a new one)?

A

set1 |= set2

set1 %= set2

set1 -= set2

set1 ^= set2

17
Q

167 How to choose a random element from a given sequence?

A

By using random.choice():

import random

t = [1, 2, 3]
print(random.choice(t))

18
Q

168 How to generate a random integer from a given interval?

A

import random

print(random.randint(5, 10))

19
Q

169 The order in which statements are executed is called the __________________?

A

flow of execution

20
Q

170 What will be printed when the following code executes?

def test(a, b = 5):

print(a, b)

test(-3)

A

-3 5

It prints the values of a and b with a space between them. The default value of b is 5.

21
Q

171 We have a list of tuples with user IDs, usernames and passwords. How can we map it into a dictionary, where keys will be usernames and values all the data belonging to that user together? What can it be useful for?

users = [(1, ‘Bob’, ‘bob12345’), (2, ‘Carl’, ‘pwdFh4’), (3, ‘Derek’, ‘cool123’)]

A

username_mapping = {user[1] : user for user in users}

print(username_mapping)

{‘Bob’: (1, ‘Bob’, ‘bob12345’), ‘Carl’: (2, ‘Carl’, ‘pwdFh4’), ‘Derek’: (3, ‘Derek’, ‘cool123’)}

It can be useful for user logins:

username_input = input(‘Please enter your username: ‘)

password_input = input(‘Please enter your password: ‘)

ID , username, password = username_mapping[username_input]

if password_input == password:

print(‘Login successful’)

else:

print(‘Your details are not correct’)

22
Q

172 How to define a function with any number of arguments?

A

def function_name(*args):

23
Q

173 How does destructuring a list into function arguments work?

A

Using asterisk:

def add(x, y):

return x +y

nums = [3, 5]

add(*nums)

24
Q

174 How does unpacking dictionary items to a function arguments work? There are 2 ways!

A
  1. Using 2 asterisks for unpacking values:

def add(x, y):

return x + y

nums = {‘x’ : 3, ‘y’ : 5}

print(add(**nums))

  1. Using one asterisk to unpack keys:

def add(x, y):

return x + y

nums = {‘x’ : 3, ‘y’ : 5}

print(add(*nums))

xy

25
175 When defining a function, how do we **combine any number of positional arguments with a named one**?
the operator is a named argument and its mandatory! the nested functions are predefined for any number of arguments def apply(\*args, operator): if operator == ‘\*’: return multiply**(\*args)** elif operator == ‘+’: return sum**(\*args)** else: print('No valid operator provided to apply()') !!! If we don't keep the asterisk in the nested functions, we get Type Error (unsupported operand type(s) for +: 'int' and 'tuple'), because the apply functions accepts the multiple arguments as a tuple (args = (1, 2, 3)) and the nested functions wrap it as another tuple (args = ((1, 2, 3), ).
26
176 What is the **difference between using \*\* in a function header and when calling the function**?
1. In the header they serve to collect named arguments into a dictionary. ``` def named(\*\*kwargs): print(kwargs) print(type(kwargs)) ``` named(name = 'Bob', age = 25) {'name': 'Bob', 'age': 25} 2. In a function call they can be used to unpack a dictionary into keyword arguments (important!!!: the keys have to be identical with the keyword arguments). ``` def named(name, age): print(name) print(age) ``` details = {'name' : 'Bob', 'age' : 25} named(\*\*details) Bob 25
27
177 What is the difference between **“\_\_str\_\_”** and **“\_\_repr\_\_”**?
**object.\_\_str\_\_(self)** Called by **str(object)** and the built-in functions **format()** and **print()** to compute the “informal” or nicely printable string representation of an object. The return value must be a string object. [...] **object.\_\_repr\_\_(self)** Called by the **repr()** built-in function to compute the “official” string representation of an object. [...] . If a class defines **\_\_repr\_\_()** but not **\_\_str\_\_()**, then **\_\_repr\_\_()** is also used when an “informal” string representation of instances of that class is required. This is typically used for debugging, so it is important that the representation is information-rich and unambiguous. So to summarize we can say: * \_\_repr\_\_ should be unambiguous (and possibly machine-readable) * \_\_str\_\_ should be human-readable * \_\_repr\_\_ is a fallback for \_\_str\_\_ if \_\_str\_\_ is missing * Calling print() uses \_\_str\_\_ --\> If you can only write one, start with \_\_repr\_\_. Another rule of thumb: \_\_repr\_\_ is for developers, \_\_str\_\_ is for customers.
28
178 What's the difference between **instance**, **class** and **static methods**?
class MyClass: def method(self): return 'instance method called', self @classmethod def classmethod(cls): return 'class method called', cls @staticmethod def staticmethod(): return 'static method called' **Instance Methods** The first method on MyClass, called method, is a regular *instance method*. That’s the basic, no-frills method type you’ll use most of the time. You can see the method takes one parameter, self, which points to an instance of MyClass when the method is called (but of course instance methods can accept more than just one parameter). Through the self parameter, instance methods can freely access attributes and other methods on the same object. This gives them a lot of power when it comes to modifying an object’s state. Not only can they modify object state, instance methods can also access the class itself through the self.\_\_class\_\_ attribute. This means instance methods can also modify class state. **Class Methods** Let’s compare that to the second method, MyClass.classmethod. I marked this method with a [@classmethod](https://docs.python.org/3/library/functions.html#classmethod) decorator to flag it as a *class method*. Instead of accepting a self parameter, class methods take a cls parameter that points to the class—and not the object instance—when the method is called. Because the class method only has access to this cls argument, it can’t modify object instance state. That would require access to self. However, class methods can still modify class state that applies across all instances of the class. **Static Methods** The third method, MyClass.staticmethod was marked with a [@staticmethod](https://docs.python.org/3/library/functions.html#staticmethod) decorator to flag it as a *static method*. This type of method takes neither a self nor a cls parameter (but of course it’s free to accept an arbitrary number of other parameters). Therefore a static method can neither modify object state nor class state. Static methods are restricted in what data they can access - and they’re primarily a way to [namespace](https://realpython.com/python-namespaces-scope/) your methods. **Key Takeaways** * Instance methods need a class instance and can access the instance through self. * Class methods don’t need a class instance. They can’t access the instance (self) but they have access to the class itself via cls. * Static methods don’t have access to cls or self. They work like regular functions but belong to the class’s namespace. * Static and class methods communicate and (to a certain degree) enforce developer intent about class design. This can have maintenance benefits.
29
179 What does !r in a string format do? return f'Device {self.name**!r**} ({self.connected\_by})'
It puts the relevant content in simple quotes. print(device1) Device **'mouse'** (usb)
30
180 What value is printed when the following code is executed? name = "Jane Doe" **def** myFunction(parameter): value = "First" value = parameter print (value) myFunction("Second")
Second
31
181 What is **deserialization**?
**Deserialization** is the process of decoding the data that is in JSON format into native data type. In Python, deserialization decodes JSON data into a dictionary (data type in python).
32
182 What is json module, loads() and dumps() methods?
33
183 What is \*args and \*\*kwargs in function definition used for and how is the \* and \*\* used in a function call?
In function definiton args and kwargs let us write functions with variable number of arguments. \*args collects extra positional arguments as a tuple. \*\*kwargs collects the extra keyword arguments as a dictionary. The actual syntax is \* and \*\*. Calling them args and kwargs is just a convention (and one you should stick to). When calling a function, the \* symbol can be used to unpack args and kwargs, ie. a tuple of positional arguments and a dictionary of keyword arguments.
34
184 How to add global variable to a function definition?
my\_var = 5 def my\_var\_func(): **global my\_var** print(my\_var) my\_var = 10 my\_var\_func() 5
35
185 What are the dir() and help() functions used for with imported modules?
dir() shows a list of methods that can be used from this module help() shows the whole description of the module