Karamzov
Karamzov

Reputation: 403

How to find longest string here?

I am trying to find the longest string in a nested list using the below code

table_data = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

cnt = [""]*3
for tab in range(len(table_data)):
    for liel in table_data[tab]:
        if len(liel) > len(cnt[tab]):
            cnt[tab]=liel
print(cnt)
# ['cherries', 'Alice', 'moose']

The above code is returning the longest string in each list, but I think its long code, is there any other way to do this?

Expecting any ways to do this using List comprehension or function

Regards

Upvotes: 2

Views: 81

Answers (2)

Vasilis G.
Vasilis G.

Reputation: 7846

Another way to achieve your result would be to use the map function, althouth this does not utilize list comprehension:

table_data = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

output = list(map(lambda data: max(data, key=len),table_data))
print(output)

Output:

['cherries', 'Alice', 'moose']

Upvotes: 1

wim
wim

Reputation: 362497

Expecting any ways to do this using List comprehension

Yes, list comprehension is a good choice.

>>> [max(row, key=len) for row in table_data]
['cherries', 'Alice', 'moose']

Upvotes: 8

Related Questions