Home > Back-end >  How to compare first and last index of a string in a list
How to compare first and last index of a string in a list

Time:09-21

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!

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

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)
  • Related