Rico Yu
Rico Yu

Reputation: 29

list comprehension fail, cannot show None

a = []
b = []
c = []
d = []
a = input('Enter first  row (enter 0 for space): ')
b = input('Enter second row (enter 0 for space): ')
c = input('Enter third  row (enter 0 for space): ')
d = input('Enter fourth row (enter 0 for space): ')

start = [int(a[0]),int(a[2]),int(a[4]),int(a[6]),
         int(b[0]),int(b[2]),int(b[4]),int(b[6]),
         int(c[0]),int(c[2]),int(c[4]),int(c[6]),
         int(d[0]),int(d[2]),int(d[4]),int(d[6])]

[None if x==1 else x for x in start]

start

Here is my code, I try to input some value like (1 2 3 4) and save it into a list, then I want to use list comprehension to turn each 1 into None. But It can't change into None when I print it.

Upvotes: 0

Views: 47

Answers (2)

user1245262
user1245262

Reputation: 7505

Or, following chepner's answer, just try

start = [None if x==1 else x for x in start]
start

Upvotes: 0

chepner
chepner

Reputation: 531255

The list comprehension doesn't modify start in-place; you need a regular for to execute a series of assignment statements instead.

for i, x in enumerate(start):
    if x == 1:
        start[i] = None

Upvotes: 1

Related Questions