Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

Writing short code

Define a function named convert that takes a list of numbers as its only parameter and returns a list of each number converted to a string.

For example, the call convert([1, 2, 3]) should return ["1", "2", "3"].

What makes this tricky is that your function body must only contain a single line of code.

 

==== SOLUTION ====

By using a simple loop to iterate over the numbers and convert each one to a string. Here’s the single-line function definition:

“`python
def convert(numbers):
       return [str(num) for num in numbers]
“`

Explanation:

– `def convert(numbers):`: This line defines a function named `convert` that takes a single parameter `numbers`, which is a list of numbers.

– `return [str(num) for num in numbers]`: This line uses a list comprehension to iterate over each number `num` in the input list `numbers`, convert it to a string using `str(num)`, and store the result in a new list. This list of strings is then returned as the output of the function.

This single line of code accomplishes the task without using `map()` by converting each number in the input list to a string using a list comprehension.

 

Join the conversation