DAT BOI
DAT BOI

Reputation: 183

Python: looping through a list?

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")

Upvotes: 2

Views: 100

Answers (3)

Blaszard
Blaszard

Reputation: 31953

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]]

Upvotes: 1

wim
wim

Reputation: 362577

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']

Upvotes: 6

Óscar López
Óscar López

Reputation: 236004

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']

Upvotes: 2

Related Questions