Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
recursion for lists
#1
my question here
Hello everyone,
I have a multi dimensional list with 4 parameters
array1 = [[array_size,full_type,child={},size],
[array_size,full_type,child1={},size],....]
where child,child1 are again lists contains [array_size,full_type,child={},size],
[array_size,full_type,child={},size]...

I have to go through this recursively until I get no child at each layer.
Any help is hightly appreciated. Thank you

my code here
Reply
#2
Please show us the code you have so far, and explain the problem you are having with it (including the full error message if there is one).
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
There are few ways to do it. If you are aware of depth at which the lists are nested you can use * operator to unpack list.

Else you can do it via recursion.
eg-

myList = [1,[["powers","of","2"],2,4,8,16,32,64],2,[["powers","of","3"],3,9,27,81,243]]

def recur_print_list(iterable):
	for i in iterable:
		#if hasattr(i,'__iter__') and not isinstance(i, str): # checks if i is iterable and not string
		#if isinstance(i, collections.Iterable) and not isinstance(i, str):

		if type(i)==type([]):
			recur_print_list(i)
		else:
			print(i)

recur_print_list(myList)
The two commented if statements do the same work.

Another way is to use exception handling.

myList = [1,[["powers","of","2"],2,4,8,16,32,64],2,[["powers","of","3"],3,9,27,81,243]]

def recur_print_list(iterable):
	try:
		if isinstance(iterable, str): #Since strings are iterable in python3
			raise TypeError
		for i in iterable:
			recur_print_list(i)
	except TypeError:
			print(iterable)
recur_print_list(myList)
Since the strings in python3 are iterable you have to take care of that.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,378 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 3,286 Mar-20-2019, 08:01 PM
Last Post: stillsen

Forum Jump:

User Panel Messages

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