This question already has answers here:
How can I provide a "callback" to an API?
(5 answers)
Closed 5 years ago.
I want to create a list of squares of even numbers by creating a list, applying the callback functions to each element of the list and puts the result in a list. But how do I implement callback in the first place?
In this case I think you are looking for the map builtin. It takes a function and a list and then applies that function on the list storing each result as it goes. For example:
def square(x):
return x * x
list(map(square, [1, 2, 3, 4]))
>>> [1, 4, 9, 16]
Note that we need to cast the result of map back to a list since it returns a map object.
Related
This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 8 months ago.
Whenever I use list methods in the print function, it gives none as an output, but if I apply methods and store in it variable before print() and then print that variable, only it will provide the desired result. Why? Let me show you what I am talking about:
l = [9, 4, 7, 1, 2]
print(l.sort())
None
But tuple can give the output in the print function.
List methods are indeed functions that modify the value of the Python list. These functions don't return any value because their purpose is to perform operations directly on the corresponding list values.
However, there are some special build-in functions like sorted() as you can see in the following example, which return the modified list, instead of just changing its values and returning None :
> l = [9, 4, 7, 1, 2]
> print(l.sort())
None
> print(sorted(l))
[1, 2, 4, 7, 9]
When you invoke list.sort(), the list is sorted but if you try to print the outcome of the function, you will find that the function is not coded to give any out value, so you will get None. As shown in the question comments, you can learn more about this behavior on the official Python documentation.
This question already has answers here:
Why can't I iterate twice over the same iterator? How can I "reset" the iterator or reuse the data?
(5 answers)
Closed 2 years ago.
Please follow along this code:
def addition(n):
return n + n
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))
Output: [2, 4, 6, 8]
Now when I apply list() again on result, which has already become a list, result turns out to be empty.
list(result)
Output: []
Why is this so?
The map object is a generator.
list(result)
involves iterating through the iterator. The iterator is now finished. When you try again, there is no data to return, so you have an empty list. If you reset the iterator in some way, you can get the expected results.
This is something like reading an entire file, and then wondering why your next read loop doesn't return anything: you're at the end.
This question already has answers here:
How to emulate sum() using a list comprehension?
(10 answers)
Closed 4 years ago.
l = [5, 7, 8, 2, 1, 4]
sum = 0
for i in l:
sum += i
print(sum)
how can I get sum of all elements but using list comprehension?
list comprehension should be used only for generating a list. You can simply use sum(l).
List comprehension always produces another list so I am not sure if you can even do that. You will surely need other function to fold the sequence into a single value.
This question already has answers here:
Why does foo.append(bar) affect all elements in a list of lists?
(3 answers)
Value changes in new list impact previous list values, within a list of lists [duplicate]
(2 answers)
Python append behaviour odd? [duplicate]
(3 answers)
Closed 4 years ago.
I have written following code for solving the n-Queens problem where we have to find all possible legal (non-attacking) placements of n queens in an n*n chessboard. The code uses the standard backtracking solution.
Here the method n_queens uses the helper method solve_n_queens which uses recursion. The outer method just initializes global lists result & col_placement and calls the helper method.
def n_queens(n):
def solve_n_queens(row):
if row == n: # all queens are legally placed
result.append(list(col_placement))
return
for col in range(n):
# check if new queen is either 1) in same column or 2) same diagonal with any previously placed queen
if all(abs(col-c) not in (0, row-r)
for r, c in enumerate(col_placement[:row])):
col_placement[row] = col
solve_n_queens(row+1)
result, col_placement = [], [0] * n # result is empty initially; [0] * n means no queen is placed
solve_n_queens(0)
return result
This gives erroneous output for n_queens(4)
[[3, 1, 2, 1], [3, 1, 2, 1]]
However it is not an algorithmic bug because just altering the 4th line result.append(col_placement) to result.append(list(col_placement)) mysteriously gives the correct output
[[1, 3, 0, 2], [2, 0, 3, 1]]
What I don't grok is when col_placement is already a list, why do we need to call the list method?
The problem is that without using list you are appending a reference to the same and only list col_placement you are working with (as you can see the results are not only wrong, but they are also the same). Using list creates a new copy (a instant snapshot of col_placement) that will not be modified when col_placement does as you keep going through the rest of the program.
So essentially list(col_placement) is the same as col_placement.copy() or col_placement[:].
This question already has answers here:
Creating functions (or lambdas) in a loop (or comprehension)
(6 answers)
Closed 6 years ago.
Is it possible that when appending lists of function objects in Python 3, the order gets lost?
My understanding was that Python lists are ordered and indeed running
numbers = []
for i in range(10):
numbers.append(i)
print(numbers)
returns [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] as expected.
If I append function objects however, like in this MWE:
functions = []
for k in range(10):
def test():
print('This is the %i th function.' %k)
functions.append(test)
and call functions[2]() I get This is the 9 th function.
Can somebody make sense of this odd behaviour?
A function closure does not capture the value of a variable when it is defined, it captures the name of the variable.
Thus, the function you have stored in functions[2] references k. When you call it, it will show you the value of k when it is called, not when it was defined.