Aug-30-2017, 08:14 AM
There are few ways to do it. If you are aware of depth at which the lists are nested you can use
Else you can do it via recursion.
eg-
Another way is to use exception handling.
*
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.