b985
b985

Reputation: 13

Appending to a list but only storing last value

There is something wrong with my control flow but i can't figure it out. I am trying to get rid of all non-numeric characters. The output is supposed to look like:

fixed_times = ['0700', '1200', '2010', '1025', '1235', '1410']

But my program is only appending '1410' to fixed_times

This is my code:

event_times = ['07:00.', '12:00.', '20:10.', '10:25.', '12:35.', '14:10.']

count = 0 
j = 0
while count < len(event_times):
    fixed_times = []
    new_time = ""

    time = event_times[j]
    i = 0
    while i < len(time):
        if time[i].isdigit():
            new_time += str(time[i])
    
        i += 1
    fixed_times.append(new_time)
    j += 1
    count += 1

print(fixed_times)

Upvotes: 0

Views: 1017

Answers (2)

stellasia
stellasia

Reputation: 5612

Your program is recreating the list fixed_times at each iteration, so the previous appended values are lost. You should move the variable declaration out of your first while loop like this:

# ...
fixed_times = []
while count < len(event_times):
   # ...

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195438

You don't need to use while, simple list comprehension is enough:

event_times = ["07:00.", "12:00.", "20:10.", "10:25.", "12:35.", "14:10."]

out = ["".join(i for i in t if i.isdigit()) for t in event_times]
print(out)

Prints:

['0700', '1200', '2010', '1025', '1235', '1410']

Or:

import re

event_times = ["07:00.", "12:00.", "20:10.", "10:25.", "12:35.", "14:10."]

out = ["".join(re.findall(r"\d", t)) for t in event_times]
print(out)

Upvotes: 0

Related Questions