w3resource

Python: Take any number of iterable objects or objects with a length property and returns the longest one

Python Regular Expression: Exercise-56 with Solution

Write a Python program that takes any number of iterable objects or objects with a length property and returns the longest one.

  • Use max() with len() as the key to return the item with the greatest length.
  • If multiple objects have the same length, the first one will be returned.

Sample Solution:

Python Code:

def longest_item(*args):
  return max(args, key = len)
 
print(longest_item('Red', 'Green', 'Black', 'Orange'))
print(longest_item([1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]))
print(longest_item([1, 2, 3], 'Java'))
print(longest_item({10, 100}, 'Python'))

Sample Output:

Orange
[1, 2, 3, 4, 5]
Java
Python

Flowchart:

Flowchart: Regular Expression -  Take any number of iterable objects or objects with a length property and returns the longest one.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous Python Exercise: Convert a given string to snake case.
Next Python Exercise: Match beginning and end of a word with a vowel.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/re/python-re-exercise-56.php