Member Avatar

user45949219

I've got a program that is designed to access a nested list and then print values from a certain column in each sublist. My problem being, I don't know how to edit this to provide more freedom with what values I wish to print out. This is how it looks currently ..

column = [['A', 'A', 'B'], ['B', 'A', ''], ['', '', 'B']]
n = 1
columns = list(zip(*column))
print(list(columns[n]))

>>> ['A', 'A', '']

I was wondering if it was possible to modify this so I could then, for example, print out the first item in sublist1, second item in sublist2 and third item in sublist 3. Giving me something like..

>>> ['A', 'A', 'B']

My original attempt at this was to to run a for loop and then try appending values through into a new list but I can't figure it out due to my novice knowledge.

Cheers in advance for the help!

First of all, unzip step doesn't really help you. You can get the ith element of each list with list comprehension:
list=[a[i] for a in column] for a given i.

To get some other set of elements as you describe will require looping through the number of elements and taking each desired element explicitly.

Use list comprehension with enumerate:

>>> column = [['A', 'A', 'B'], ['B', 'A', ''], ['', '', 'B']]
>>> print [item[ind] for ind, item in enumerate(column)]
['A', 'A', 'B']
>>>