Sriram Rajendran
Sriram Rajendran

Reputation: 91

how can I replace all zeros in a list with hundred in python?

listzero = [0,0,0,0,0]

for q in listzero:
    if (q==0):

        print("zero is present ")
        listzero.remove(0)
        listzero.append(100)


    else:
        print("non zero list")

print(listzero)

Output:

zero is present 
zero is present 
zero is present 
non zero list
non zero list
[0, 0, 100, 100, 100]

My Expected output is

zero is present 
zero is present 
zero is present
zero is present 
zero is present 
[100, 100, 100, 100, 100]

Upvotes: 1

Views: 9204

Answers (6)

Vasilis G.
Vasilis G.

Reputation: 7846

Try this one too:

listzero = [0,0,0,0,0]
listzero = list(map(lambda i: 100 if i==0 else i, listzero))
print(listzero)

The result is:

[100, 100, 100, 100, 100]

Upvotes: 1

Myles Hollowed
Myles Hollowed

Reputation: 546

for n in range(len(listzero)):
    if listzero[n] == 0:
        listzero[n] = 100

This will edit your current list in place in case you don't want to create another one.

A more pythonic variant using enumerate:

for n,v in enumerate(listzero):
    if not v:
        listzero[n] = 100

Upvotes: 2

Mikhail Borisov
Mikhail Borisov

Reputation: 50

Assuming you want to do it in place (which means directly substitute 0 with 100):

listzero = [0,0,0,0,0]

for i in range(len(listzero)):
    if (listzero[i] == 0):
        listzero[i] = 100
        print("zero is present ")
    else:
        print("non zero list")
print(listzero)

More "Pythonic" way to do it using list comprehension:

listzero = [0,0,0,0,0]

listzero = [100 for x in listzero if x == 0 else x] # we overwrite listzero here

Upvotes: 0

M. Matt
M. Matt

Reputation: 77

This should work fine:

newlist = [100 if x == 0 else x for x in listzero]

Upvotes: 1

Ajax1234
Ajax1234

Reputation: 71451

You can try this:

listzero = [0,0,0,0,0]
final_list = [i if i != 0 else 100 for i in listzero]

Output:

[100, 100, 100, 100, 100]

Upvotes: 4

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

listzero.remove(0)

removes the first 0 element, but

listzero.append(100)

adds 100 at the end of the list (plus the fact that you shouldn't change the list while iterating, except for item assignment, since it confuses the loop internal index)

Other answers show how to change values within a loop, but you can also use a list comprehension instead. It doesn't replace the list, but creates another one, here with an idiomatic expression (since we test the 0 value) to set to 100 when 0 appears (thanks to the or operator):

listzero = [0,0,100,200,300]
listzero = [x or 100 for x in listzero]

(I've set different values to demonstrate the code, and assigning it back to the original list name to "overwrite" it)

result:

[100, 100, 100, 200, 300]

Upvotes: 6

Related Questions