top of page

Python (7): Map




Welcome to my Python tutorial again! This time we'll explore another function that can serve as a similar role of list comprehesion.


For more dedicated explaination of list comprehesion, please see my another tutorial list comprehesion.




Let's start with a quick example:


def add1(self, nums: List[int]):
    return map(int, str(int(''.join()map(str, nums)) + 1))


add1() is a function that tries to transform a list integer [1, 2, 3] into [1, 2, 4] (example).


nums is an integer list [1, 2, 3].


map(str, nums) first transforms each integer in nums list into a string.


''.join() then joins all strings in nums list into a single string.


int() then transforms the joint string into an integer.


str(), of course, transforms the integer back into a string.


Lastly, there's another map() to transform each character of the string into an integer.


It further generates the integers into an iterable map object.


It means now all integers are deemed as a single, split, list-like elements.



However, a map object is not yet a list, so we we need to use list() to convert it into a real list to see the output:



return list(map(int, str(int(''.join()map(str, nums)) + 1)))


Now, the output sucessfully change from [1, 2, 3] to [1, 2, 4].












Congratulations on completing this tutorial!


You've gained valuable knowledge and skills that will empower you in your coding journey.



See you in Python (8)!








© 2023 Harmony Pang. All rights reserved.








Comments


bottom of page