Python - List Comprehensions Versus map

Introduction

ord function returns the integer code point of a single character.

print( ord('s') )

To collect the ASCII codes of all characters in an entire string.

You can use a simple for loop and append the results to a list:

Demo

res = [] 
for x in 'test': 
    res.append(ord(x))                # Manual results collection 
# from   w  ww .  j  a va  2  s  .  c o m
print( res )

Result

Or you can use map function to get similar results:

Demo

res = list(map(ord, 'test'))          # Apply function to sequence (or other) 
print( res )

Result

Or by using list comprehension expression:

Demo

res = [ord(x) for x in 'test']        # Apply expression to sequence (or other) 
print( res )

Result

List comprehensions returns the results of applying an arbitrary expression to an iterable of values.

List comprehensions is convenient when applying an arbitrary expression to an iterable instead of a function:

Demo

d=[x ** 2 for x in range(10)] 
print( d )

Result

Here, we've collected the squares of the numbers 0 through 9.

To use a map call:

Demo

d=list(map((lambda x: x ** 2), range(10))) 
print( d )

Result

Related Topic