list1 = ['abc','def','ghi','jk'`] output is : list2 = ['adgj','behk','cfi']
Basically each element
list2 should be the ith character in each element of
I know the general format would be something along the lines of creating list2 with the following element until the end of each.
[list1 [list1 [list1
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)): list2[I]=list1[I]
I know I need a second for loop to change for index 0, having trouble implementing that
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 "") result.append(''.join(element)) print(result)
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 ""
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=''))) print(result)
['adgj', 'behk', 'cfi']
Albeit, the latter is a bit advanced solution.
You can either do this using
itertools.zip_longest as @juanpa.arrivillaga said in the comments:
list(map(''.join, zip_longest(*list1, fillvalue='')))
result = [''] * max(map(len, list1)) for i in range(len(list2)): for s in list1: if i < len(s): result[i] += s[i]