1

I have a list like below:

L = [1,2,3,[1,2],15,[1,[5,6]],[],[[]],5]

I want to add the int values only together. I can extract the items in the nested lists but when I get to a nested list like [[]] or empty list [], I get IndexError: list index out of range. How do I either skip the lists that are empty or set their value to 0 when I check them?

I tried:

l2 = [[]]
if not l2:
    # do something

but this only works if the list is a single list [].

anonom
  • 125
  • 11
A.J1234
  • 11
  • 1
  • https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists – Stephen Rauch Jul 13 '18 at 00:56
  • 1
    If you show the code that you wrote to add all the ints together, we could show you how to fix it to handle empty lists. Without that, we can't really do anything except give you vague hints, or write a completely different implementation that you may not even understand. – abarnert Jul 13 '18 at 00:58
  • 1
    There's a million ways to handle this. The wayt I would do it is to write a `flatten` function that flattens the list, then simply `sum(flatten(L))` – juanpa.arrivillaga Jul 13 '18 at 01:02
  • @Muzol That's not true. It returns `False` if a list doesn't have any truthy values. So it's `False` for `any([])`, but it's also `False` for `any([0, 0, 0])`. – abarnert Jul 13 '18 at 01:15
  • @juanpa.arrivillaga is right. There are many ways this could be done - some better than others. I'd perfer his method, but if you need something simpler, iterate over `L` and check if the current element is 'truthy' (e.g. `if l:`). If the element is truthy, then add it's values to some variable which stores the total sum of all non-empty list. – Christian Dean Jul 13 '18 at 01:34

0 Answers0