Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
recursion for lists
#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


Messages In This Thread
recursion for lists - by lavanya - Aug-29-2017, 10:42 AM
RE: recursion for lists - by ichabod801 - Aug-29-2017, 12:52 PM
RE: recursion for lists - by hbknjr - Aug-30-2017, 08:14 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,531 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,415 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