Ashley
Ashley

Reputation: 57

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

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!:(

Upvotes: 1

Views: 49

Answers (3)

Rock
Rock

Reputation: 33

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.

Upvotes: 1

965311532
965311532

Reputation: 546

Try this:

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

# Output
# 'hrua'

Upvotes: 1

YoshiMbele
YoshiMbele

Reputation: 999

The enumerate function is your friend docs here:

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

Upvotes: 0

Related Questions