Q151 - 300 Flashcards
(35 cards)
151 What does filter() function do and what is its syntax?
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]
152 What is a list comprehension and what is its syntax?
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])
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’}]}
list_compri = [person[‘name’] for person in tester[‘info’]]
154 What does zip() function do and what is its syntax?
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}
155 What does sum() function do and what is its syntax?
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
156 How can we flatten a list of lists (put all elements into one list) using list comprehension?
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’]
157 How can we modify all elements of list of lists and put them into one list?
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)
158 How can we modify each element of list of lists and keep them in sub-lists?
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]]
159 How do we find all possible pairs of users from a list of them?
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’)]
160 How do we create a nested list with list comprehension? How do we change the number of nested levels?
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]]]]
161 What is “if __name__ == ‘__main__’:” expression used for?
It is used to execute some code only if the file was run directly, and not imported.
162 What does strftime() function do?
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/
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”)
only II.
164 What is the output from the following code?
a = 3
b = (a != 3)
print(b)
False
165 What are the alternative operators for operations with sest?
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
166 How to modify a set with operations (instead of creating a new one)?
set1 |= set2
set1 %= set2
set1 -= set2
set1 ^= set2
167 How to choose a random element from a given sequence?
By using random.choice():
import random
t = [1, 2, 3]
print(random.choice(t))
168 How to generate a random integer from a given interval?
import random
print(random.randint(5, 10))
169 The order in which statements are executed is called the __________________?
flow of execution
170 What will be printed when the following code executes?
def test(a, b = 5):
print(a, b)
test(-3)
-3 5
It prints the values of a and b with a space between them. The default value of b is 5.
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’)]
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’)
172 How to define a function with any number of arguments?
def function_name(*args):
173 How does destructuring a list into function arguments work?
Using asterisk:
def add(x, y):
return x +y
nums = [3, 5]
add(*nums)
174 How does unpacking dictionary items to a function arguments work? There are 2 ways!
- Using 2 asterisks for unpacking values:
def add(x, y):
return x + y
nums = {‘x’ : 3, ‘y’ : 5}
print(add(**nums))
- Using one asterisk to unpack keys:
def add(x, y):
return x + y
nums = {‘x’ : 3, ‘y’ : 5}
print(add(*nums))
xy