Celine
Celine

Reputation: 1

How to compare first and last index of a string in a list

input :['slx', 'poo', 'lan', 'ava', 'slur'] output:['s', 'o', 'l', 'a', 'r'] how do you compare the first and last index of a string in a list?

Thanks in advance!

Upvotes: 0

Views: 827

Answers (3)

Syed Mahfuzur Rahman
Syed Mahfuzur Rahman

Reputation: 477

Assuming that you want to find the smallest value (compared between first and last character) from a string inside a list:

to do this

list = ['slx', 'poo', 'lan', 'ava', 'slur']
result=[]

for item in list:
    leng = len(item)
    if item[0] < item[leng-1]:
        result.append(item[0])
    else:
        result.append(item[leng-1])
print(result)

Upvotes: 0

Dmitry Erohin
Dmitry Erohin

Reputation: 137

s = ['slx', 'poo', 'lan', 'ava', 'slur']
print(list(map(lambda x: min(x[0], x[-1]), s)))

Upvotes: 1

j1-lee
j1-lee

Reputation: 13939

I am assuming that you want to compare the characters and get the 'smaller' one (lexicographically). You can use list comprehension and min for that:

lst = ['slx', 'poo', 'lan', 'ava', 'slur']
output = [min(x[0], x[-1]) for x in lst]
print(output) # ['s', 'o', 'l', 'a', 'r']

Comparing two strings is done lexicographically: for example, 'banana' < 'car' == True, since "banana" comes before "car" in a dictionary. So for example, 's' < 'x', so min('s', 'x') would be 's', which explains the first element of the output list.

Upvotes: 3

Related Questions