The error comes from this: range(len(otro)+1)
. When you use range
, the upper value isn't actually iterated, so when you say range(5)
for instance, your iteration goes 0, 1, 2, 3, 4
, where position 5
is the element 4
. If we then took that list elements and said for i in range(len(nums)+1): print nums[i]
, the final i
would be len(nums) + 1 = 6
, which as you can see would cause an error.
The more 'Pythonic' way to iterate over something is to not use the len
of the list - you iterate over the list itself, pulling out the index if necessary by using enumerate
:
In [1]: my_list = ['one', 'two', 'three']
In [2]: for index, item in enumerate(my_list):
...: print index, item
...:
...:
0 one
1 two
2 three
Applying this to your case, you can then say:
>>> for index, item in enumerate(otro):
... dik[dato[index]] = item
However keeping with the Pythonicity theme, @mgilson's zip
is the better version of this construct.