lighting
lighting

Reputation: 35

python, for loop and list append

I am trying to extract a part of a string and append it to a list (message). But at the end, what I see is just one item appended (the last one) to the list. Below is my code. What am i doing wrong?

for item in all_text:
    message = []
    if len(item) < 2:
        continue
    else:
        m_temp = item.split(']')[1].split(':')
        if len(m_temp) <= 1:
            continue
        else:
            message.append(m_temp[1])
    print(len(message))
    print(message)

Upvotes: 2

Views: 121

Answers (2)

Mahmoud Nasr
Mahmoud Nasr

Reputation: 642

move the message = [] above the for loop and align the two print with the For

Upvotes: 1

Daniel Walker
Daniel Walker

Reputation: 6782

You're redefining message to be an empty list with each iteration of your for loop. Therefore, all of your previous appends will be lost except for the one on the last iteration.

Try moving message = [] to right before your for loop.

Upvotes: 0

Related Questions