Home > database >  How to access values from nested list using for loop
How to access values from nested list using for loop

Time:04-22

I have one of problem statement

List =[[[1,2],[3,4]]]

And i want 1st index from both nested list in list a and 2nd index from both nested list in list b using for loop and if else not using append()

Like:

a = [1,3]
b = [2,4]

CodePudding user response:

How about this:

l = [[[1,2],[3,4]]]
a = []
b = []
for x in l[0]:
   a.append(x[0])
   b.append(x[1])

There is more pythonic way to do this, but code above is written to make it understandable.

CodePudding user response:

If you write

a=[List[0][0][0], List[0][1][0]]
b=[List[0][0][1], List[0][1][1]]

You get what you want. You can define it in a loop, of course

CodePudding user response:

l = [[[1,2],[3,4]]]
a = [x[0] for x in l[0]]
b = [x[1] for x in l[0]]

List comprehensions are essentially for loops in lists they pretty much read like a sentence:

do x FOR x in OTHER_LIST (and wrap that in a list)
  • Related