1

If I have a list/array such as:

B = [[1,2,3,4],[2,3,4,5],[4,3,2,4]] 

(there are 50 elements in total)

I only want to show the 2nd value of each element. e.g. 3,4,2

I have tried something like B([:,2]) but I keep getting an error "TypeError: list indices must be integers or slices, not tuple"

I was thinking I might have to use some sort of loop?

3
  • Tuple indexing works for numpy arrays. Lists don't take those. Instead, you can index each sublist in a list comprehension. Commented Oct 27, 2017 at 16:40
  • 2
    print([i[2] for i in B]) Commented Oct 27, 2017 at 16:41
  • I have done that and it is showing all values in column 3, but If I want to change all the values in column 3 to '0' how would I do this? Commented Oct 27, 2017 at 19:32

3 Answers 3

3

List comprehensions for the rescue:

result = [i[2] for i in B]
Sign up to request clarification or add additional context in comments.

1 Comment

I now have it showing me the 2nd value in each element but do you know how I would replace that value (say with 0) and then write the data back to my original array/list B?
1

In Python 3.x

list(zip(*B))[2]

In Python 2.x

zip(*B)[2]

Output:

(3, 4, 2)

Comments

0

Using List Comprehension :

#`n` is the row
>>> [row[n] for row in B]

#driver value :

IN : B = [[1,2,3,4],[2,3,4,5],[4,3,2,4]]
IN : n = 2
OUT : [3, 4, 2]

Comments

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.