0

This for loop works fine but not as a list comprehension. The comprehension creates empty elements for each iteration. Can someone explain what is wrong and how to fix it?

def GetAsciiList():
    num_list = []
    for num in range(32, 42, 1):
        num_list.append((str(num), chr(num)+" "))
    return num_list

def GetAsciiListLC():
    num_list = []
    num_list = [(num_list.append((str(num), chr(num)+" "))) for num in range(32, 42, 1)]
    return num_list

print GetAsciiList()
print GetAsciiListLC()

console output:

[('32', '  '), ('33', '! '), ('34', '" '), ('35', '# '), ('36', '$ '), ('37', '% '), ('38', '& '), ('39', "' "), ('40', '( '), ('41', ') ')]
[None, None, None, None, None, None, None, None, None, None]
ksha
  • 2,007
  • 1
  • 19
  • 22
wdog
  • 5
  • 4
  • 1
    Can you edit your question to format your Python code? Python is whitespace-sensitive and it's hard to know how to correctly edit this question. – NicholasM Feb 01 '20 at 19:39
  • List comprehensions resolve to a list. So you probably just want `return [(str(num), chr(num)+" ") for num in range(32, 42, 1)]`. If you append in the list comprehension, the result of the appending, `None` will be the value for each item in the list, as you are seeing. – audiodude Feb 01 '20 at 19:42

1 Answers1

2

Consider this line in GetAsciiListLC():

num_list = [(num_list.append((str(num), chr(num)+" "))) for num in range(32, 42, 1)]

num_list.append((str(num), chr(num)+" "))) mutates the list and returns None.

I think what you want is this:

def GetAsciiListLC():
    """ Return list of 2-tuples containing numbers and ASCII equivalents, both as strings. """
    return [(str(num), chr(num) + " ") for num in range(32, 42)]

See this question for the rationale of returning None from the list.append() method: Why does append() always return None in Python?

NicholasM
  • 4,557
  • 1
  • 20
  • 47