Python Forum
Making list empty after return in function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Making list empty after return in function
#2
There are different solutions, but I prefer to use a closure and a helper function like so
def flatten(to_flatten):
    result = []

    def helper(nested_list):
        for i in nested_list:
            if type(i) != list:
                result.append(i)
            else:
                helper(i)
        return result

    return helper(to_flatten)
Alternatively, you could have a second parameter which defaults to None, and you have have logic which creates the result variable when that parameter is None and then provide it for the recursive calls. I prefer the method I've coded here because it does not change the interface given to clients of the code, who might accidentally provide a second parameter (or who might notice it and wonder).
Reply


Messages In This Thread
RE: Making list empty after return in function - by micseydel - Nov-24-2018, 07:25 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How do I calculate a ratio from 2 numbers and return an equivalent list of about 1000 Pleiades 8 15,858 Jan-05-2024, 08:30 PM
Last Post: sgrey
  Code with empty list not executing adeana 9 3,814 Dec-11-2023, 08:27 AM
Last Post: buran
  nested function return MHGhonaim 2 674 Oct-02-2023, 09:21 AM
Last Post: deanhystad
  return next item each time a function is executed User3000 19 2,455 Aug-06-2023, 02:29 PM
Last Post: deanhystad
  function return boolean based on GPIO pin reading caslor 2 1,246 Feb-04-2023, 12:30 PM
Last Post: caslor
  Making a function more efficient CatorCanulis 9 1,971 Oct-06-2022, 07:47 AM
Last Post: DPaul
  set.difference of two list gives empty result wardancer84 4 1,574 Jun-14-2022, 01:36 PM
Last Post: wardancer84
  Showing an empty chart, then input data via function kgall89 0 1,004 Jun-02-2022, 01:53 AM
Last Post: kgall89
  displaying empty list vlearner 5 1,735 Jan-19-2022, 09:12 AM
Last Post: perfringo
  Remove empty keys in a python list python_student 7 3,156 Jan-12-2022, 10:23 PM
Last Post: python_student

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020