2

I have a list, example:

mylist=["a", "b", "end"]

I want to append all values of mylist to a different list (new_list) and also add the string " letter" to each value of the new_list except the last one (value: end)

So far I have a for loop that adds the string "letter" to all values:

new_list = []

for x in my_list:
   new_list.append(x + " letter")

which produces:

("a letter", "b letter", "end letter")

I want:

("a letter", "b letter", "end")

1
  • Why does the list contain 'end'? Simply having the list terminate would arguably be much clearer. Commented Apr 12, 2016 at 3:06

3 Answers 3

6

This is best achieved with list comprehensions and slicing:

>>> new_list = [s + ' letter' for s in mylist[:-1]] + mylist[-1:]
>>> new_list
['a letter', 'b letter', 'end']
Sign up to request clarification or add additional context in comments.

1 Comment

Hmm, all these temporary lists... avoids the temporaries - [s + ' letter' if i < len(mylist)-1 else s for i, s in enumerate(mylist)] but equally ugly.
2

We have to skip the last element, use list slices for this; using a list comprehension will also come in handy. Try this:

mylist   = ['a', 'b', 'end']
new_list = [x + ' letter' for x in mylist[:-1]] + [mylist[-1]]

It works as expected:

new_list
=> ['a letter', 'b letter', 'end']

Comments

1

You can add " letter" to each of your element in a list except the last one, and then just add the last one.

new_list = [x + " letter" for x in my_list[:-1]] + [my_list[-1]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.