bwrr
bwrr

Reputation: 621

Why does this for loop only work if it iterates at the zeroth index?

I have a list:

oldlist = ['do gs\n','ca ts\n','monk eys\n','fro     gs\n','\n','lio     ns\n','tige rs\n','she ep\n']

I'm trying to extract only the first portion of the list ['do gs\n', 'ca ts\n', 'monk eys\n', 'fro gs\n'] before the newline '\n'.

This is my code and it outputs the correct solution:

oldlist = ['do gs\n','ca ts\n','monk eys\n','fro     gs\n','\n','lio ns\n','tige rs\n','she ep\n']
print("Before Loop: ", oldlist)
newlist = []
for iter in oldlist:
    if '\n' in iter[0]:
        break
    else:
        newlist.append(iter)

print("After Loop: ", newlist)

However the line which begins from

if '\n' in iter[0]: 

is the one which I do not understand how it works. Why does this loop only work when iter[0]? Why is it that if I just iterate over iter it outputs only a blank list?

OUTPUT if "iter[0]" used:

Before Loop:  ['do gs\n', 'ca ts\n', 'monk eys\n', 'fro gs\n', '\n', 'lio ns\n', 'tige rs\n', 'she ep\n']
After Loop:  ['do gs\n', 'ca ts\n', 'monk eys\n', 'fro gs\n']

OUTPUT if "iter" used :

Before Loop:  ['do gs\n', 'ca ts\n', 'monk eys\n', 'fro gs\n', '\n', 'lio ns\n', 'tige rs\n', 'she ep\n']
After Loop:  []

Also if I do this:

for iter in oldlist:
     print(iter[0])

It spits out only d from the first string do gs\n

So in summary, what is going on behind the scenes that is allowing iter[0] to iterate through the oldlist to give the correct solution in newlist?

Upvotes: 0

Views: 49

Answers (2)

janbrohl
janbrohl

Reputation: 2656

Your iter[0] means the first character in each string while iter means each full string. eg 'do gs\n'[0] means 'd' and of course in 'do gs\n' there is a '\n'.

You can also use the shorter newlist=oldlist[:oldlist.index("\n")] instead of your loop.

Upvotes: 0

Dunno
Dunno

Reputation: 3684

The in operator when used on strings checks if a given character exists at all in the string. So \n in "do gs\n" evaluates to true, because there is a newline character in this string. However, if you check for \n in "do gs\n"[0] it only checks if the first character is the newline.

It would be more clear if you simply did if iter == '\n' since that's basically what you're doing.

Upvotes: 2

Related Questions