1

Give the code below:

array = [[0, 2], [3, 4]]
for i in array:
    print '%d' % i[0][0]

I am getting the error: TypeError: 'int' object has no attribute '__getitem__'

but if I change to print'%d' %i I get the error: TypeError: %d format: a number is required, not list

How am I supposed to cycle through the array and print the first and second value of each sub array?

Thanks

1
  • 2
    i is an element in array, therefore (in this case) it can only have one subscript. BTW, array is the name of a standard library module so a bad choice for a variable name. Commented May 9, 2016 at 21:56

5 Answers 5

2
array = [[0, 2], [3, 4]]
for sub_array in array:
    print sub_array[0], sub_array[1]

or even better:

array = [[0, 2], [3, 4]]
for sub_array in array:
    print sub_array
Sign up to request clarification or add additional context in comments.

Comments

2

i is 1-dimensional. Therefore:

 print '%d' % i[0] 

PS. It's not really clear what is your desired output. This solution will print the first element of every list.

Comments

1

You want print '%d %d' % (i[0], i[1])

Comments

1

First, the statement for x in y loops over y and and assigns x to the value in y that you're currently looping on e.g. y = [1, 2, 3] for x in y: print x would give the output: 1 2 3 4 thus, in your case array = [[0, 2], [3, 4]] for i in array: print '%d' % i[0][0] """ i is [0, 2] on the first iteration making i[0] = 0 i[0][0] -> TypeError: %d format: a number is required, not list changing this to i would obvious lead to i being a list that you're attempting to assign as a number -> TypeError: %d format: a number is required, not list """

What you really meant to do was stop at i[0] making the code: array = [[0, 2], [3, 4]] for i in array: print '%d' % i[0]

As for your question, how to iterate over the array and print the values, well you can do something like: array = [[0, 2], [3, 4]] for subarray in array: for element in subarray: print element

Comments

0

If you'd like to keep your loop, you can do:

array = [[0, 2], [3, 4]]
for i in array:
    print '%d' % i[0] 

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.