user3091216
user3091216

Reputation: 85

List Manipulation wrong output

I wrote this block:

stst = "Hello World!@#"

empt = []

def shplit(stst):
    tst = stst.split()
    print tst
    for i in tst:
        empt = list(i)
    print empt


shplit(stst)

what I get from the prints is:

['Hello', 'World!@#']
['W', 'o', 'r', 'l', 'd', '!', '@', '#']

I can't figure out why the word 'Hello' doesn't appear at all in the second list. Why is this happening??

Upvotes: 0

Views: 20

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 121966

Your indentation is incorrect:

for i in tst:
    empt = list(i)
print empt # this happens after the loop

When you print empt, the loop has finished, so you only see the value from the last iteration of the loop. If you want to see all iterations, indent the print one level:

for i in tst:
    empt = list(i)
    print empt # this happens inside the loop

Alternatively, if you want to fill empt with all of the various is, use list.extend:

for i in tst:
    empt.extend(i)
print empt

This gives:

>>> shplit(stst)
['Hello', 'World!@#']
['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd', '!', '@', '#']

Upvotes: 1

Related Questions