This is not the way to do things in Python, but surely - you can traverse a list of lists recursively:

def findList(lst, ele):
    if not lst:         # base case: the list is empty
        return False
    elif lst[0] == ele: # check if current element is the one we're looking
        return True
    elif not isinstance(lst[0], list): # if current element is not a list
        return findList(lst[1:], ele)
    else:                              # if current element is a list
        return findList(lst[0], ele) or findList(lst[1:], ele)
Answer from Óscar López on Stack Overflow
🌐
Codecademy
codecademy.com › learn › learn-recursion-python › modules › recursion-python › cheatsheet
Learn Recursion with Python: Recursion: Python Cheatsheet | Codecademy
When the base case is reached, print out the call stack list in a LIFO (last in first out) manner until the call stack is empty. Using another while loop, iterate through the call stack list.
Discussions

python - Iterate a list using recursion - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
May 23, 2017
python - Recursively iterate over lists - Stack Overflow
I'm expecting to see a flat list of parents, in the order they are found: ... In this case, A has two parents: E & B. Iterate over both two get their parents, so the result would be: ... I'm sure I'm passing in too much recursively, but can't figure out exactly what. More on stackoverflow.com
🌐 stackoverflow.com
python - Iterating through list of list - Stack Overflow
It sounds like you need to use recursion. Make a function to iterate through a list, and if it hits an item that is also a list, call itself to iterate on the member. Here's a link to something similar: http://www.saltycrane.com/blog/2008/08/python-recursion-example-navigate-tree-data/ More on stackoverflow.com
🌐 stackoverflow.com
Recursive function to iterate over a list
How to write a recursive function, which iterates over a list and checks if an element is in that list in elixir? More on elixirforum.com
🌐 elixirforum.com
6
0
November 8, 2021
Top answer
1 of 2
1

but I wonder if it's okay there's no "return" line under "else:"

Yes, that's OK. You don't need to return anything from your function if you don't want to. In fact, in the interest of consistency, you may as well remove the thing returned in the if block too:

def printElement(inputlist):
        newlist=inputlist
        if len(newlist)==0:
                return
        else:
                removedElement=newlist[len(inputlist)-1]
                newlist=newlist[:len(inputlist)-1]
                Element=printElement(newlist)
                print(removedElement)


collection = ['hey', 5, 'd']

printElement(collection)

Is it better code with or without the newlist?

Assigning new things to inputlist won't modify it outside of the function, so there's no harm in doing so. May as well get rid of newlist.

def printElement(inputlist):
        if len(inputlist)==0:
                return
        else:
                removedElement=inputlist[len(inputlist)-1]
                inputlist=inputlist[:len(inputlist)-1]
                Element=printElement(inputlist)
                print(removedElement)


collection = ['hey', 5, 'd']

printElement(collection)

you don't use Element after assigning it, so you may as well not assign it at all.

def printElement(inputlist):
        if len(inputlist)==0:
                return
        else:
                removedElement=inputlist[len(inputlist)-1]
                inputlist=inputlist[:len(inputlist)-1]
                printElement(inputlist)
                print(removedElement)


collection = ['hey', 5, 'd']

printElement(collection)

You don't really need to modify inputlist, since you only use it once after modifying it. Just stick that expression straight into the printElement call. And now that inputlist is never modified, you can get rid of removedElement too, and just inline its expression in the print function.

def printElement(inputlist):
        if len(inputlist)==0:
                return
        else:
                printElement(inputlist[:len(inputlist)-1])
                print(inputlist[len(inputlist)-1])


collection = ['hey', 5, 'd']

printElement(collection)

Fun fact: for any list x, x[len(x)-1] can be shortened to x[-1]. Same with x[:len(x)-1] to x[:-1].

def printElement(inputlist):
        if len(inputlist)==0:
                return
        else:
                printElement(inputlist[:-1])
                print(inputlist[-1])


collection = ['hey', 5, 'd']

printElement(collection)

Since the first block unconditionally returns, you could remove the else and just put that code at the function level, without changing the code's behavior. Some people find this less easy to read. Personally, I like my code to have the least amount of indentation possible.

def printElement(inputlist):
        if len(inputlist)==0:
                return
        printElement(inputlist[:-1])
        print(inputlist[-1])


collection = ['hey', 5, 'd']

printElement(collection)

That's about as compact as you can get, with a recursive solution. You should probably just stick with the iterative version, for a few reasons:

  • Fewer lines
  • More easily understood
  • Doesn't raise a "maximum recursion depth exceeded" exception on lists with 200+ elements
2 of 2
1

Your function is needlessly complicated. The return value is never used. You also print from the end of the list, which is a bit odd: tail recursion is a more usual style. For example:

def printCollection(c):
    if c:
        print c[0]
        printCollection(c[1:])

This still has the flaw that it copies the list for every element in the list, making it an O(n^2) function. It's also limited to data structures that use slices and indices. Here's a recursive version that prints any iterable:

def printCollection(c):
    it = iter(c)
    try:
        el = it.next()
        print el
        printCollection(it)
    except StopIteration:
        pass

It's still a bit odd to recurse here as this is a naturally iterative problem.

🌐
Stack Overflow
stackoverflow.com › questions › 26600404 › iterate-a-list-using-recursion
python - Iterate a list using recursion - Stack Overflow
May 23, 2017 - How can I write this same function using recursion? def replace(thelist,a,b): """Returns: a COPY of thelist but with all occurrences of a replaced by b. Example: replace([1,2,3,1], 1, 4) = [...
🌐
UCI
ics.uci.edu › ~thornton › ics32 › Notes › Recursion
ICS 32 Winter 2022, Notes and Examples: Recursion
Python is not one of them, however; in Python, your first inclination should be to use loops to solve problems of repetition. However, what you soon discover is that not all problems lead to a well-formulated solution this way. Particularly when you find yourself needing to iterate through recursive data structures like our nested list ...
🌐
Readthedocs
understanding-recursion.readthedocs.io › en › latest › 07 Lists of Lists.html
Summing a List of Lists — Understanding Recursion Using Python 1.0 documentation
Let’s say that L == [1, [2, 3]]. ... call, so at this point total == 1. The next run through the loop triggers the recursive call, sending e == [2, 3] to frame 2. In frame 2, we skip the if clause and iterate over the list, adding each item of e to total....
Find elsewhere
🌐
DevCodevi
devcodevi.com › home › questions › iterating through list of list in python
Iterating through list of list in Python - DevCodevi
http://www.saltycrane.com/blog/2008/08/python-recursion-example-navigate-tree-data/ ... x = [u'sam', [['Test', [['one', [], []]], [(u'file.txt', ['id', 1, 0])]], ['Test2', [], [(u'file2.txt', ['id', 1, 2])]]], []] layer1=x layer2=[] while True: for i in layer1: if isinstance(i,list): for j in i: layer2.append(j) else: print i layer1[:]=layer2 layer2=[] if len(layer1)==0: break ... (note that it didn’t look into the tuples for lists because the tuples aren’t lists.
🌐
Reddit
reddit.com › r/learnpython › i made a recursive function!
r/learnpython on Reddit: I made a recursive function!
November 26, 2020 -

I'm pretty new to programming and still feel a bit shaky when it comes to recursive functions. I was reviewing some documentation on lists and saw that len() will only count "top level" items in a list, i.e. if your list contains a dict or another list, it won't count the number of items in the nested list or dict.

I thought it might be fun (and good practice) to try writing a function that will count every item, no matter how nested it was. I realized quickly that I should try using recursion, and after some fiddling around I made something that works!

I know it's not groundbreaking but I'm proud of the progress I'm making and just wanted to share.

def listcounter(x):
    counter = 0
    for i in x:
        if type(i) == list or type(i)==dict:
            counter = counter + listcounter(i)
    else:
        counter = counter + 1
    return counter

Top answer
1 of 5
15
Looks good, and makes sense. Indentation is very important in python and the else: aligned with for is valid syntax but not what you are looking for (hopefully this is just a cut and paste error). Note: python also has isinstance() which can take multiple types, e.g.: def listcounter(x): counter = 0 for i in x: if isinstance(i, (list, dict)): counter += listcounter(i) else: counter += 1 return counter If you feel comfortable you could use the ternary operator instead of the if. They are equivalent but as both clauses are changing counter it is a probably just a matter of preference: def listcounter(x): counter = 0 for i in x: counter += listcounter(i) if isinstance(i, (list, dict)) else 1 return counter This can be collapsed to a sum() but this is pushing things in terms of readability: def listcounter(x): return sum(listcounter(i) if isinstance(i, (list, dict)) else 1 for i in x) You can also be more abstract and use typing.Iterable to indicate anything that you can iterate over, so this would also work for sets and tuples (but you do have to exclude str and bytes), e.g.: import typing def listcounter(x): counter = 0 for i in x: if isinstance(i, typing.Iterable) and not isinstance(i, (str, bytes)): counter += listcounter(i) else: counter += 1 return counter
2 of 5
2
One of the more bizzare things is how multiple software engineers have given me advice to avoid recursion where possible. For something simple it's no big deal. For complex stuff, it's easy to get stuck a few levels down
🌐
Python Forum
python-forum.io › thread-30159.html
Using recursion instead of for loops / list comprehension
So I’ve been learning about symmetric differences between lists which can be accomplished in a number of different ways using for loops, list comprehension, sets the exclusive or carat. Pretty neat stuff. Now I am exploring recursion. Wrapping ...
Top answer
1 of 2
1

If you are starting with two lists and want to compare them element-wise you can use zip() to simplify your life. It will give you back the elements paired off. So if you are starting with two lists, you can zip them:

list1 = ['A', 'T']
list2 = ['C', 'G']

zipped = list(zip(list1, list2))
# zipped is [('A', 'C'), ('T', 'G')]

#or use a list comprehension:
zipped = [pair for pair in  zip(list1, list2)]

zip() returns an iterator which is why it's wrapped in list() above. If you use it in a loop or other situation calling for a interator, you don't need to do that.

If you want to compare these you can use a dictionary that defines which letter maps to the other, this will allow you write a much simpler test function:

# Define a mapping that describes which elements belong togethre
pairs = {
    'G':'T',
    'T':'G',
    'C':'A',
    'A':'C'
}

list1 = ['A', 'A', 'T', 'C', 'G', 'C', 'T', 'A']
list2 = ['C', 'G', 'G', 'A', 'C', 'A', 'C', 'T']

# make a new list if the pairs line up with the mapping:
legal = [(a, b) for a, b in  zip(list1, list2) if pairs[a] == b ]

# legal pairs: [('A', 'C'), ('T', 'G'), ('C', 'A'), ('C', 'A')]

There's not much reason to do this recursively, but you of course can. Since zip() returns an iterator (pairs below) you can call next() on it to get there next value and then pass the iterator back. It will throw a StopIteration error when it's out of items, so that can be the edge condition of the recursion:

def buildList(pairs, mapping):
    ''' Takes an iterator and mapping, returns a list of legal items defined by mapping '''
    try:
        a_pair = next(pairs)  # get first item from zipped list
    except StopIteration:   # no more items, just return an empty list
        return []

    a, b = a_pair            
    if mapping[a] == b:    
        return [(a, b)] + buildList(pairs, mapping)
    else: 
        return buildList(pairs, mapping)


list1 = ['A', 'A', 'T', 'C', 'G', 'C', 'T', 'A']
list2 = ['C', 'G', 'G', 'A', 'C', 'A', 'C', 'T']
pairs = {'G':'T','T':'G','C':'A','A':'C'}

buildList(zip(list1, list2), pairs) # use zip to make the zipped iterator
2 of 2
0

This question is tagged with recursion and here's my take on it -

def head(xs = []):
  return xs[0]

def tail(xs = []):
  return xs[1:]

def check_pair(x = "", y = "", swap = True):
  if x == "A" and y == "C":
    return True
  elif x == "G" and y == "T":
    return True
  else:
    return swap and check_pair(y, x, False)

def check_valid(a = [], b = []):
  if (not a) or (not b):
    return
  elif check_pair(head(a), head(b)):
    yield (head(a), head(b))
    yield from check_valid(tail(a), tail(b))
  else:
    yield from check_valid(tail(a), tail(b))


a = ['A', 'A', 'T', 'C', 'G', 'C', 'T', 'A']
b = ['C', 'G', 'G', 'A', 'C', 'A', 'C', 'T']

print(list(check_valid(a,b)))
# [('A', 'C'), ('T', 'G'), ('C', 'A'), ('C', 'A')]

This is intuitive, but like zip, the tail function creates intermediate values. We can reduce memory requirement by using a simple index, i -

def check_pair(x = "", y = "", swap = True):
  if x == "A" and y == "C":
    return True
  elif x == "G" and y == "T":
    return True
  else:
    return swap and check_pair(y, x, False)

def check_valid(a = [], b = [], i = 0):
  if i >= min(len(a), len(b)):
    return
  elif check_pair(a[i], b[i]):
    yield (a[i], b[i])
    yield from check_valid(a, b, i + 1)
  else:
    yield from check_valid(a, b, i + 1)

a = ['A', 'A', 'T', 'C', 'G', 'C', 'T', 'A']
b = ['C', 'G', 'G', 'A', 'C', 'A', 'C', 'T']

print(list(check_valid(a,b)))
# [('A', 'C'), ('T', 'G'), ('C', 'A'), ('C', 'A')]

You may be interested in this related Q&A

🌐
Reddit
reddit.com › r/learnpython › is it possible to iterate over a list of lists in a function?
r/learnpython on Reddit: Is it possible to iterate over a list of lists in a function?
May 31, 2021 -

I have this exercise I am tring online which take a bunch of lists and zip them together. first and then returns a list. For example, the input func([1,2,3], [20,30,40], ['a', 'b', 'c']) should return [1, 20, 'a', 2, 30, 'b', 3, 40, 'c']

However I do not know how to iterate over the list. I don't even know if it's possible. I tried

def func(*args):
    for n in args:
        ans = list(zip(n))
        return ans

But I just get : [(1,), (2,), (3,)]

🌐
W3Schools
w3schools.com › python › python_lists_loop.asp
Python - Loop Lists
Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the index by 1 after each iteration.
🌐
GeeksforGeeks
geeksforgeeks.org › python › iterate-over-a-list-in-python
Iterate over a list in Python - GeeksforGeeks
This method allows us to access each element in the list directly. We can access all elements using for loop and in keyword to traverse all elements ... a = [1, 3, 5, 7, 9] # On each iteration val # represents the current item/element for val in a: print(val) ... This method is similar to the above method. Here we are using a while loop to iterate through a list.
Published   December 27, 2025
🌐
HackerNoon
hackernoon.com › recursion-vs-looping-in-python-9261442f70a5
Recursion vs. Looping in Python | HackerNoon
January 17, 2019 - One of the most fundamental tools in programming is a loop. While there are many different types of loops, almost each type of loop has the same basic function: iterating over data to analyze or manipulate it. Recursion is another popular type of function and although it can also analyze and ...
🌐
Reddit
reddit.com › r/learnpython › traversing an arbitrarily nested list
r/learnpython on Reddit: traversing an arbitrarily nested list
August 18, 2020 -

Hey all,

Was reading through a Python textbook and the author posted a problem about taking a list that potentially is very deeply nested (e.g. [[[[[[[[[[[[[[[[[[[[[[[1,3,4,5],[4]....) and writing a script to sum up all those numbers (I don’t believe built-in sum works on nested lists). I made the problem a bit more general — how do you take an arbitrarily nested list and strip out all the extra structure to get a list of minimal depth? (E.g., the above would be [1,3,4,5,4...]

I came up with this.

def structureSlayer(L):
	L2 = []
	for item in L:
		try: L2.extend(structureSlayer(item))
		except: L2.append(item) 
	return L2

idea is that it gets top-level elements of a list, then tries to iterate over those elements (which works if they’re lists themselves). It spits out an error it tries to loop over a single element, like “4” in the above list, which is caught by except and taken out of the nested for loop function calls. Essentially each call to structureSlayer reduces the depth (if possible) of all list elements by 1.

  1. I glanced at the sample code after I did the above, and the author has an explicit type test (testing if each item is a list type, then going deeper into the recursion). Aren’t type tests frowned upon in Python? It didn’t seem to simplify the code at all and maybe costs some flexibility?

  2. This code also works if there’s, say, a string somewhere in my list, and I don’t fully understand why. Eventually (after nesting some amount of for loops with repeated structureSlayer calls, it seems like item is going to hit a string, split it into single-character strings, and then loop endlessly over those (a single-character string is still iterable?) Why does the loop terminate if L = [1,[2,’hey’]], for instance?