Creating a list where each list[j] is the character j from each element in another list of strings

by Lizzy   Last Updated October 09, 2019 17:26 PM

For example:

list1 = ['abc','def','ghi','jk'`] 
output is : list2 = ['adgj','behk','cfi']

Basically each element i in list2 should be the ith character in each element of list1.

I know the general format would be something along the lines of creating list2 with the following element until the end of each.



However, when I try to create for loops it says that I am out of index and am also struggling with getting the index to stop if the last element in list1 is smaller size than the rest of the elements. I just need some direction on how to set up the for loops?

for I in range(Len(list1)):

I know I need a second for loop to change for index 0, having trouble implementing that

Answers 2

You could do something like this:

list1 = ['abc','def','ghi','jk']

max_length = max(map(len, list1))

result = []
for i in range(max_length):
    element = []
    for s in list1:
        element.append(s[i] if i < len(s) else "")


The outer loop iterates over all the possible indices, the inner loop iterates over the words, the line:

s[i] if i < len(s) else ""

retrieves s[i] if i is in bounds. Although the most pythonic (as mentioned by @juanpa.arrivillaga) way is to do:

from itertools import zip_longest

list1 = ['abc', 'def', 'ghi', 'jk']

result = list(map(''.join, zip_longest(*list1, fillvalue='')))



['adgj', 'behk', 'cfi']

Albeit, the latter is a bit advanced solution.

Daniel Mesejo
Daniel Mesejo
October 08, 2019 17:47 PM

You can either do this using itertools.zip_longest as @juanpa.arrivillaga said in the comments:

list(map(''.join, zip_longest(*list1, fillvalue='')))

Or manually:

result = [''] * max(map(len, list1))
for i in range(len(list2)):
    for s in list1:
      if i  < len(s):  result[i] += s[i]
October 08, 2019 17:51 PM

Related Questions

Updated October 09, 2018 04:26 AM

Updated November 14, 2017 11:26 AM

Updated October 08, 2019 06:26 AM

Updated March 16, 2019 19:26 PM

Updated May 25, 2017 17:26 PM