Longest Iterable Object Identification

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this challenge, you will write a function that takes any number of iterable objects or objects with a length property and returns the longest one.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FunctionsGroup -.-> python/keyword_arguments("`Keyword Arguments`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13683{{"`Longest Iterable Object Identification`"}} python/keyword_arguments -.-> lab-13683{{"`Longest Iterable Object Identification`"}} python/lists -.-> lab-13683{{"`Longest Iterable Object Identification`"}} python/tuples -.-> lab-13683{{"`Longest Iterable Object Identification`"}} python/function_definition -.-> lab-13683{{"`Longest Iterable Object Identification`"}} python/build_in_functions -.-> lab-13683{{"`Longest Iterable Object Identification`"}} end

Longest Item

Write a function longest_item(*args) that takes any number of iterable objects or objects with a length property and returns the longest one. The function should:

  • Use max() with len() as the key to return the item with the greatest length.
  • If multiple items have the same length, the first one will be returned.
def longest_item(*args):
  return max(args, key = len)
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'

Summary

In this challenge, you learned how to write a function that takes any number of iterable objects or objects with a length property and returns the longest one. You used max() with len() as the key to return the item with the greatest length. If multiple items have the same length, the first one will be returned.

Other Python Tutorials you may like