Add longest_item snippet
This commit is contained in:
20
snippets/longest_item.md
Normal file
20
snippets/longest_item.md
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
---
|
||||||
|
title: longest_item
|
||||||
|
tags: list,string,utility,intermediate
|
||||||
|
---
|
||||||
|
|
||||||
|
Takes any number of iterable objects or objects with a length property and returns the longest one.
|
||||||
|
If multiple objects have the same length, the first one will be returned.
|
||||||
|
|
||||||
|
Use `max()` with `len` as the `key` to return the item with the greatest length.
|
||||||
|
|
||||||
|
```py
|
||||||
|
def longest_item(*args):
|
||||||
|
return max(args, key = len)
|
||||||
|
```
|
||||||
|
|
||||||
|
```py
|
||||||
|
longest_item('this', 'is', 'a', 'testcase') # 'testcase'
|
||||||
|
longest_item([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]) # [1, 2, 3, 4, 5]
|
||||||
|
longest_item([1, 2, 3], 'foobar') # 'foobar'
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user