Sep-18-2020, 10:45 AM
Thank you, @ndc85430, this helps tremendously.
Based on your feedback, here is the next iteration of my script:
By the way, I noticed that when the first function is inserted in between lines 6 and 7, the script still runs and processes the text file just as well.
I still have a few questions about my new script.
At line 7, the first argument inside the
Exploring
Based on your feedback, here is the next iteration of my script:
def replace_n(set_st): return str.replace(set_st, "\n", "") def tail(filename, nums): with open(filename, 'r') as lines: result = lines.readlines()[-(nums):] result_without_n = list(map(replace_n, result)) return result_without_n print(tail('Alice.txt', 3))This achieves the same thing as my original script but with a regular function instead of a lambda. Here is the output:
Quote:['including how to make donations to the Project Gutenberg Literary', 'Archive Foundation, how to help produce our new eBooks, and how to', 'subscribe to our email newsletter to hear about new eBooks.']
By the way, I noticed that when the first function is inserted in between lines 6 and 7, the script still runs and processes the text file just as well.
I still have a few questions about my new script.
At line 7, the first argument inside the
map()
built-in must be an iterable. Iterables are usually data structures such as strings, lists, tuples, among others. But this script, replace_n()
is a function. Is it really possible to iterate over a function even when the return value of the replace_n()
function is not a string, list, or tuple? At line 2, the replace()
method of the str
built-in is called with an empty argument, set_st
. How is this possible? Why does Python continue to iterate successfully over the replace_n()
function when the return value includes an empty argument? I’d expect Python to cough up Type Error since replace_n()
is not an iterable. To phrase my confusion in another way: set_st
is initialized at line 1 but when it is referred to at line 2, there is no value being passed in. It’s just empty. Why does the set_st
argument work if it is empty? When the replace_n()
function is called at line 7, no argument is specified.Exploring
map()
, I came across another tutorial on Geeks for Geeks which I’ve been playing with but still don’t understand how Python is able to iterate over a function (or lambda expression):def addition(n): ''' Return double of n ''' return n + n # We double all numbers using map() numbers = (1, 2, 3, 4) result = map(addition, numbers) print(list(result)) # Square all numbers using map() and lambda numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 20) result = map(lambda x: x * x, numbers) print(list(result))Output:
Quote:[2, 4, 6, 8]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 400]