0
y = [[0,0,0],
     [0,0,0]]

p = [1,2,3,4,5,6]

y[0] = p[0,2]
y[1] = p[3,4]

Returns error I want to assign values in p to y, how to do that?

The answer should be y = [[1,2,3],[4,5,6]]

Thank you very much!

2
  • 2
    First of all, it would be nice to know the language you are working in. Commented Sep 13, 2013 at 2:22
  • Python, I want to slice p and put each in y Commented Sep 13, 2013 at 2:25

3 Answers 3

1

Your array slicing is using the wrong syntax. It should be:

y[0] = p[0:3]
y[1] = p[3:6]
  1. Use : to slice arrays. Using , goes between dimensions, and p is not a 2-dimensional array!
  2. End slices include the start, exclude the end. So 0:2 has only elements 0 and 1.
Sign up to request clarification or add additional context in comments.

Comments

1

In Python, colon (:) is used to slice arrays: I think this is what you are looking for:

y = [[0,0,0], [0,0,0]]
p = [1,2,3,4,5,6]
y[0] = p[0:3]
y[1] = p[3:6]

Comments

0
y = []
p = [1,2,3,4,5,6]

y.append(p[:3])
y.append(p[3:])

print y 

--output:--
[[1, 2, 3], [4, 5, 6]]

If you don't specify a value in the first position of a slice, python uses 0, and if you don't specify a value in the second position of a slice, python grabs the remainder of the list.

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.