How to add strings to a list?

Can somebody explain why the code below prints out " to conquer me home. " instead of every line?

for line in love_maybe_lines:
line.strip()
print(line)

Yet, when the code below adds every line to the empty list.

love_maybe_lines_stripped =
for line in love_maybe_lines:
love_maybe_lines_stripped.append(line.strip())

Your first example does not append anything to a list, just prints the unchanged line. strip() is not an insitu operation but one that needs to be redirected to a variable or a print statement.

for line in love_maybe_lines:
    print (line.strip())

line, itself is not modified. Only the printed value is stripped.

We’re not instructed to modify the original list, only to create a spinoff list of modified strings.

for line in love_maybe_lines:
    love_maybe_lines_stripped.append(line.strip())

as the solution has shown. In either event, we had to redirect (assign) the outcome to some other object or process. APPEND assigns it to a list; PRINT passes it as an argument to a process (in Python 3 it is a function). The act of stripping has no effect upon the object being stripped.

I had this code first and I don’t understand why having two lines doesn’t work. My code was the same as the solution.

love_maybe_lines_stripped =

for line in love_maybe_lines:

line.strip()
love_maybe_lines_stripped.append(line)

print(love_maybe_lines_stripped)

I may even answer my own question but did anyone else think this way?

Hello! Is the below code not working because of the += function cannot be used to append strings. Is it only to add integers to a variable? TIA!

love_maybe_lines = ['Always    ', '     in the middle of our bloodiest battles  ', 'you lay down your arms', '           like flowering mines    ','\n' ,'   to conquer me home.    ']

love_maybe_lines_stripped = []
for line in love_maybe_lines:
  love_maybe_lines_stripped += love_maybe_lines.append(line.strip())
  
print(love_maybe_lines_stripped)

  
  

Thanks. But aren’t these just strings just elements in a list? Why does it throw the error here?

The purpose of the list.append() method is to add an item to the list from which it is called. However that method always returns None. Therefore the value of this expression is None:

love_maybe_lines.append(line.strip())

Consequently this statement attempts to concatenate None to the list love_maybe_lines_stripped:

  love_maybe_lines_stripped += love_maybe_lines.append(line.strip())

You can concatenate a list to a list, but cannot concatenate None to a list.

There are other problems with the statement as well, one of them being that the list.append() method attempts to increase the size of the list love_maybe_lines as the for loop iterates through it, which could lead to an infinite loop.

Choose either list concatenation with square brackets to enclose the item that you wish to add to love_maybe_lines_stripped or, preferably, the list.append() method for this task, but not both.

Edited on June 17, 2019 to make it clear that the for loop is what performs the iteration through love_maybe_lines, while the list.append() method attempts to increase its size

1 Like

Thanks for that response.

Trying to follow what you’re saying. First, I still don’t understand why this returns None.

The purpose of the list.append() method is to add an item to the list from which it is called. However that method always returns None . Therefore the value of this expression is None :

To me, it seems like the code should be adding items from the list love_maybe_lines. There are items in the list, afterall.

I do understand your below point. I’m increasing the size of love_maybe_lines with its own items which could end up infinite.

Finally, your last point.

I’m not sure about what the square brackets method would look like?

Thank You!!

Lists may be concatenated to other lists…

print ([1, 2, 3, 4] + [9, 8, 7, 6])
# [1, 2, 3, 4, 9, 8, 7, 6]

Notice that above both literals are square bracketed data structures.

To add to a list we either append a value, or we concatenate the value with a list wrapper, as in square brackets.

 my_list += ['value']
2 Likes

Methods, like other functions, can perform actions. Regardless of what actions they perform, all functions return a value. Quite often, when the primary purpose of a method is to alter the value of an object in some way or to produce output, that method returns the value None. That is the case with the list.append() method. Its action is to add an item to the end of a list, and its return value is None.

Let’s consider this line of code:

  love_maybe_lines_stripped += love_maybe_lines.append(line.strip())

With the += operator, that line attempts to concatenate to the love_maybe_lines_stripped list, the value returned by the following method call :

love_maybe_lines.append(line.strip())

As noted above, the list.append() method always returns None. Therefore, that line of code is attempting to concatenate None to the love_maybe_lines_stripped list.

That call to the list.append() method, if successful, would also add the value of line.strip() to the love_maybe_lines list, which is the list through which you are iterating. Therefore, each time the loop progresses through an item that list, the list would grow longer, and the end would never be reached.

If you wish to use the += to perform the desired task, you can do so. To the left of the operator, you already have love_maybe_lines_stripped, which is correct. To the right of the operator, you must enclose, within a list, the item that you wish to add to love_maybe_lines_stripped. This is necessary so that you can concatenate a list to a list.

Just put square brackets, [, and ], around line.strip(). Then you can place the result of doing that to the right of the += operator, and that is all that needs to be placed there.

In summary, to the left of the += operator, you would have:

love_maybe_lines_stripped

To the right of the operator would be:

[line.strip()]
3 Likes

I’m confused as to what the mistake is I’m making in that I get a “result does not match expected”. My concern is that I’m adding spaces somewhere before the line break but don’t know how to check that. My code looks like:

love_maybe_lines = ['Always ‘, ’ in the middle of our bloodiest battles ‘, ‘you lay down your arms’, ’ like flowering mines ‘,’\n’ ,’ to conquer me home. ']

def stripper(lst):
y=
for x in lst:
y.append(x.strip())
return y

love_maybe_lines_stripped=(stripper(love_maybe_lines))

def joiner(lst):
y=’’
for x in lst:
y=y+’’.join([x,’\n’])
return y

love_maybe_full=joiner(love_maybe_lines_stripped)

print(love_maybe_full)

Having googled the appearance of the poem, my output matches that so I feel like I’m adding extra spaces somewhere, I just don’t know how/why. Thank you

Compare to,

love_maybe_full = '\n'.join(love_maybe_lines_stripped)

@ruby1218558829, when you post code, it will be much more readable as Python if you use the </> icon that appears in the menu bar of the box you are typing in. Also, your code can then be copied and pasted for easy testing.

You can see what is printed including all newlines by using the repr() function with your print() statement, for example:

love_maybe_lines = ['Always    ', '     in the middle of our bloodiest battles  ', 'you lay down your arms', '           like flowering mines    ','\n' ,'   to conquer me home.    ']
def stripper(lst):
    y= []
    for x in lst:
        y.append(x.strip())
    return y
love_maybe_lines_stripped=(stripper(love_maybe_lines))
def joiner(lst):
    print(lst)
    y=''
    for x in lst:
        y=y+ ''.join([x,'\n'])
    return y
love_maybe_full=joiner(love_maybe_lines_stripped)

print(repr(love_maybe_full))

Output: (Be sure to scroll all the way to the end to see what is happening.)

'Always\nin the middle of our bloodiest battles\nyou lay down your arms\nlike flowering mines\n\nto conquer me home.\n'

Bottom line: It (the grader) does not like the fact that there is a terminal newline. If you join with ‘\n’ as suggested by @mtf, that will be avoided.

2 Likes

I am not sure why this is returning wrong. When I use the print all of the white space is gone.

love_maybe_lines = ['Always    ', '     in the middle of our bloodiest battles  ', 'you lay down your arms', '           like flowering mines    ','\n' ,'   to conquer me home.    ']
love_maybe_lines_stripped = []
for i in love_maybe_lines:
  var = [i.strip()]
  love_maybe_lines_stripped.append(var)
  
print(love_maybe_lines_stripped)

I found my mistake. var = i.strip() instead of var = [i.strip()]