1

How would I find the values from a certain column in an array? For example I have:

[1, 1, 2, 4, 1, 7, 1, 7, 6, 9]
[1, 2, 5, 3, 9, 1, 1, 1, 9, 1]
[7, 4, 5, 1, 8, 1, 2, 0, 0, 4]
[1, 4, 1, 1, 1, 1, 1, 1, 8, 5]
[9, 0, 0, 0, 0, 0, 1, 1, 9, 8]
[7, 4, 2, 1, 8, 2, 2, 2, 9, 7]
[7, 4, 2, 1, 7, 1, 1, 1, 0, 5]
[3, 4, 5, 3, 4, 5, 9, 1, 0, 9]
[0, 0, 5, 1, 1, 1, 9, 7, 7, 7]

If I wanted to list all of the values of column 5, how would I do this? I have figured out how to do this for the rows, but for the columns it is tricky, since they are all part of a separate list. I have not been able to find anything about this and I am very new to Python so I don't really know what I don't know.

6
  • 2
    A code golf answer: list(zip(*list_2d))[4] Commented Feb 17, 2018 at 4:58
  • 2
    An actual answer: use a list comprehension. [x[4] for x in list_2d] Commented Feb 17, 2018 at 4:59
  • This super works! Thank you! Just so I understand this better, what exactly is that function doing? Commented Feb 17, 2018 at 5:04
  • The first is a neat transposition trick. The second is a straightforward list comp iteration over each sublist. Commented Feb 17, 2018 at 5:06
  • Ok so if I wanted to display the value of a certain cell, would I apply the same sort of rule? Commented Feb 18, 2018 at 4:46

2 Answers 2

2

It's simple. Just use l[i][4] to print 5th column value.

l = [
            [1, 1, 2, 4, 1, 7, 1, 7, 6, 9],
            [1, 2, 5, 3, 9, 1, 1, 1, 9, 1],
            [7, 4, 5, 1, 8, 1, 2, 0, 0, 4],
            [1, 4, 1, 1, 1, 1, 1, 1, 8, 5],
            [9, 0, 0, 0, 0, 0, 1, 1, 9, 8],
            [7, 4, 2, 1, 8, 2, 2, 2, 9, 7],
            [7, 4, 2, 1, 7, 1, 1, 1, 0, 5],
            [3, 4, 5, 3, 4, 5, 9, 1, 0, 9],
            [0, 0, 5, 1, 1, 1, 9, 7, 7, 7]
        ]

for i in l:
    print(i[4])

# or simply use

[i[4] for i in l] #as pointed out by @COLDSPEED

# the above code will create a list with values from 5th column

See it in action here

Sign up to request clarification or add additional context in comments.

Comments

0

For a two dimensional array, you can use array[row][column].

2 Comments

He wants to display a complete column and not a single element
for i in range(len(list)): print list[0][i] for the first column

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.