Python Forum

Full Version: loop through list or double loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So. Brainfart here atm.

I have a list of which I don't if it consist out of (all) nested lists or just simple values.

So
listA = ["a", "b", "c"]
or
listA = [list1, list2 ]
list1=["a", "342"]
list2=["2fasd", "adf3gfds"]


If have to run a function I defined of those values of the single list hierachy (so listA (only the first example), list1, list2)

I can't check isinstance(listA, list) because both are lists. So I have to check if at all this is true, and if so: are there any nested lists. and if so: do that function there.

for i in list:
//do function

I've done some any(l in list) for l in listA but that does nothing.

Hope it makes sense.
It's not clear what you're trying to do. Could you show some code, along with what the output is vs your expected output?

If it's just iterating over a list of lists, then a for loop works fine:
>>> fruit = ["spam", "eggs", "ham"]
>>> veggies = ["gross", "green", "not-chocolate"]
>>> consumables = [fruit, veggies]
>>> for sublist in consumables:
...   for item in sublist:
...     print(item)
...
spam
eggs
ham
gross
green
not-chocolate
Yeah I figured, typing without example is bs, sorry for that. Let me try again.

#inputlist comes from another program which could either be a single list like inputlist_a or like inputlist_b BUT could also be a presented with nested lists like inputlist_c
inputlist_a = ["sheet1", "sheet2", "sheet3"]
inputlist_b = ["sheet124", "sheet1233", "sheet12373"]
inputlist_c = [a, b]

#since I don't know the input I'm going to name this INPUT


if isinstance(INPUT, list):
	for i in INPUT:
		if isinstance(i, list)
			for j in i:
				domyfunction(j) 
		else
			domyfunction(i)

#so in case of inputlist_a:
#domyfunction loops sheet1, sheet2, sheet3
#so in case of inputlist_b:
#domyfunction loops sheet124, sheet1233, sheet12373
#so in case of inputlist_c:
#domyfunction loops sheet1, sheet2, sheet3 THEN sheet124, sheet1233, sheet12373
Does that not work for you? It looks fine, as long as things can only be nested one level. Any more than that, and I'd rather use a recursive function.
aaannndd some coffee and backing away from my problem solved it.

The error I got was "expecting 'view' but got List[object]", now 'view' is a program-specific name but I was using a list. 100% sure.

Now:
I did use a list, my coding above did work.
HOWEVER I used a function which also has another variable. No problem, however I used a listobject there.

So I was looking at the wrong 'list'-issue.

Solution: for v, fp in zip(lista, listc) etc.etc.


pfff.