+ 1
Nested lists
How can I print lists within a list? Using for loop, it only prints out the outer list arranged vertically while the inner list remain the way it is. How can I make everything come out vertically? This is for Python.
15 Respuestas
+ 5
Recursive approach:
https://code.sololearn.com/cWUWW8Rih7Y1/?ref=app
It will be slower for bigger lists tho
+ 4
Mbrustler that's what recursive functions are for, you do something recursively rather than doing it by hand.
So here, you'd call the function again if the type of an element is a list. It works for lists of any dimension.
+ 2
i still dont understand what you exactly mean do you want something like this ?
https://code.sololearn.com/cpy0mhgGjC4O/?ref=app
+ 2
okay thanks a lot.
+ 2
i know but writing it helps for under standing the basic structure
i would menton but dont know how to XD
+ 2
Yash Kandalkar, you rocked this. :)
+ 1
can you give an example?
do you mean like
a = [[1,2],[3,4]]
and you want
1234 as output or [1,2],[3,4]?
+ 1
Let's say I have this:
Closefriends = ["andy", "valerie", "hector", "christina"["damien", "kimm"["lowry","donald"]]]
Now when I printed, andy, valerie, hector and Christina printed like this:
andy
valerie
hector
christina.
the rest stayed as nested list and still had the square brackets.
+ 1
and you want to print without the lists?
+ 1
I want to print the nested list the same way I printed the first four lists.
+ 1
Yeah, something like this, but with kimm, lowry and donald arranged vertically just as valerie , hector, christina, and damien are arranged.
+ 1
l = [1, 2, [3, 4], 5, 6]
for el in l:
if type(el) == list:
print(*el, end=' ')
else:
print(el, end=' ')
One way would be this.
If even the embedded lists contain lists, that won't work obviously.
+ 1
well i will try some more but thats how much i can do for now code has been updated
+ 1
#Let's say I have this:
Closefriends = ["andy", "valerie", "hector", "christina",["damien", "kimm",["lowry","donald"]]]
for x,y in enumerate(Closefriends):
if type(y) == list:
for k in y:
if type(k) == list:
for s in k:
print(s)
else:
print(k)
else:
print(y)
this is another way but it works just for nested lists of 3rd grade