Printing a string which is formed by taking each successive letter in the list of words based on the position of the word?

Viewed 37

For example:

list = ['how', 'are', 'you', 'today']

output: hrua

printing the index0 of the first word and index1 of second word and so on...

please help!:(

3 Answers

Using list comprehension and lambda function:

result = lambda list: [item[i] for i, item in enumerate(list)]

Or as a normal function

def bar(list):
    return [item[i] for i, item in enumerate(list)]
result = bar(....)

This returns the letters in a list. If you want to print them:

l = ["how","are","you","today"]
for index, value in enumerate(l):
    print(value[index])

You need to consider that this does not check for validity. If we look at the array:

["a", "b"]

This will return an error, as "b" only has index 0, and no index 1.

Try this:

l = ["how","are","you","today"]
"".join([x[i] for i, x in enumerate(l)])

# Output
# 'hrua'

The enumerate function is your friend docs here:

l = ["how","are","you","today"]
for index, value in enumerate(l):
    print(value[index])
Related