1

I am trying to make a vector out of two different ones as shown in the piece of code below. However, I get a list out of range exception on the 5th line the first time the code goes in the for loop.

What am I doing wrong?

def get_two_dimensional_vector(speeds, directions):
    vector = []
    for i in range(10):
        if (i % 2 == 0):
            vector[i/2][0] = speeds[i/2]
        else :
            vector[i/2 - 1/2][1] = directions[i/2 - 1/2]
5
  • Use enumerate in the loop Commented Dec 6, 2015 at 12:50
  • [i/2 - 1/2] in the final line should be replaced by [(i - 1)/2] for starters. Commented Dec 6, 2015 at 12:53
  • If it's integer division, you don't even need to do that. It will round down anyway. Commented Dec 6, 2015 at 12:54
  • The problem is that the OP uses a list of lists whereas the vector is only a list. That's why he gets the out of index error. I am not sure if the duplicated question has something to do with this one. Commented Dec 6, 2015 at 12:57
  • @Tasos: it will throw a list out of range error even before it has a chance to access the second dimension(index). Commented Dec 6, 2015 at 13:48

1 Answer 1

0

You can't use a Python list this way. It's not like a C array with a predefined length. If you want to add a new element, you have to use the append method or something.

Aside from that, you're also using a second index, implying that the elements of vector are themselves lists or dicts or something, before they've even been assigned.

It looks like you want to convert speeds and directions to a two-dimensional list. So, first, here's how to do that with a loop. Note that I've removed the fixed-size assumption you were using, though the code still assumes that speeds and directions are the same size.

def get_two_dimensional_vector(speeds, directions):
    vector = []
    for i in range(len(speeds)):
        vector.append([speeds[i], directions[i]])
    return vector

speeds = [1, 2, 3]
directions = [4, 5, 6]

v = get_two_dimensional_vector(speeds, directions)
print(v)

Now, the Pythonic way to do it.

print(zip(speeds, directions))
Sign up to request clarification or add additional context in comments.

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.