0

For example, I have the following list.

list=['abc', 'def','ghi','jkl','mn']

I want to make a new list as:

newList=['adgjm','behkn','cfil']

picking every first character of each element forming a new string then appending into the new list, and then with the second character of every element and so on:

Thanks for the help.

3 Answers 3

4

One way is zipping the strings in the list, which will interleave the characters from each string in the specified fashion, and join them back with str.join:

l = ['abc', 'def','ghi','jkl']

list(map(''.join, zip(*l)))
# ['adgj', 'behk', 'cfil']

For strings with different length, use zip_longest, and fill with an empty string:

from itertools import zip_longest
l = ['abcZ', 'def','ghi','jkl']

list(map(''.join, zip_longest(*l, fillvalue='')))
# ['adgj', 'behk', 'cfil', 'Z']
Sign up to request clarification or add additional context in comments.

3 Comments

IIRC map is not really considered pythonic. It's a very simple and readable answer though.
@yatu I agree. I'm not adverse in using map myself, just saying some might not consider map pythonic to the first comment.
@c4f4t0r It's a noteworthy distinction, but Python 2 is already sunsetted in 2020, so the relevant conversation should be for Python 3 unless version is specifically mentioned.
1

You can try this way:

>>> list1 =['abc', 'def','ghi','jkl']
>>> newlist = []
>>> for args in zip(*list1):
...     newlist.append(''.join(args))
... 
>>> newlist
['adgj', 'behk', 'cfil']

Or using list comprehension:

>>> newlist = [''.join(args) for args in zip(*list1)]
>>> newlist
['adgj', 'behk', 'cfil']

Comments

0

You can try this:

list=['abc', 'def','ghi','jkl']
n = len(list[0])
newList = []
i = 0
for i in range(n):
    newword = ''
    for word in list:
        newword += word[i]
    newList.append(newword)

print(newList)

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.