0

I have a list like this:

a = ["a","b","c","d","e"]

How do I insert a word to the end of each item in the list and make them as list itself?

Expected output:

a = [("a","TEST"),("b","TEST"),("c","TEST"),("d","TEST"),("e","TEST")]

I have tried a lot of ways but no luck getting that.

4 Answers 4

9

Create a tuple with the item and the desired word:

word = "TEST"
a = ["a","b","c","d","e"]
new_a = [(i, word) for i in a]

Output:

[('a', 'TEST'), ('b', 'TEST'), ('c', 'TEST'), ('d', 'TEST'), ('e', 'TEST')]

Alternatively, using map:

new_a = list(map(lambda x: (x, "TEST"), a))
Sign up to request clarification or add additional context in comments.

3 Comments

Sorry for bothering again, is there any way to eliminate the space between 'a', and 'TEST'? I need to unpack it for the classifier function
@KennyC the space is natural Python syntax. ('a', 'TEST') is equivalent to ("a","TEST").
Don't use map. List comprehensions are more pythonic
2

Another way is using zip_longest from itertools module like below (but the solution to go with should be Ajax1234's one using tuple in a list comprehension):

from itertools import zip_longest

l = ['a', 'b', 'c', 'd', 'e']
res = list(zip_longest(l, ['TEST'], fillvalue='TEST'))

Output:

>>> res
[('a', 'TEST'), ('b', 'TEST'), ('c', 'TEST'), ('d', 'TEST'), ('e', 'TEST')]

Comments

1

You can use zip:

a = ["a","b","c","d","e"]
new_a = zip(a, ["TEST"] * len(a))

output:

[('a', 'TEST'), ('b', 'TEST'), ('c', 'TEST'), ('d', 'TEST'), ('e', 'TEST')]

Comments

1

Not very hip, but similar to other common languages:

a = ["a","b","c","d","e"]
b = []

for x in a:
    b.append ( (x, 'TEST'))

a = b

print a

1 Comment

maybe add two lists inst the solution

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.