0

Suppose i have this list a = ["test", "news", "hello"] and i need to duplicate each value in list and separate it by delimiter like this.

a = [("test","test"),("news","news"),("hello","hello")]

I have tried this and got only up to this.

a = ["test", "news", "hello"]

b = [l + (''.join(l,)) for l in a]

print(b)

#['testtest', 'newsnews', 'hellohello']
1
  • Do you actually what a tuple of two items per element, or a single string separated by , for each element... Commented Jul 6, 2014 at 7:23

2 Answers 2

4

You can do it as:

a = ["test", "news", "hello"]

>>> print [(i,)*2 for i in a]   #thanks to @JonClements for the suggestion
[('test', 'test'), ('news', 'news'), ('hello', 'hello')]
Sign up to request clarification or add additional context in comments.

2 Comments

I'd go for (i,)*2 for flexibility (for increasing the amounts if ever needed)
You're welcome... the other option the OP could be after is [','.join((i,) * 2) for i in a]
2

I think the most "pythonic" (and shortest) way to do this is with everyone's favorite confusing built-in, zip:

a = ["test", "news", "hello"]
print zip(a,a) 
>>> [('test', 'test'), ('news', 'news'), ('hello', 'hello')]

And, for completeness, I'll point out that in python 3, zip returns an iterable. So to get it to print nicely, you'll want to listify it: list(zip(a,a)). If, however, you want to iterate through it, doing things with the data, you'll want to keep the iterable. (Potentially massive memory savings for long lists).

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.