Just like I’m allowed to do this:
(EDIT – I’m NOT allowed to do this either, sorry messed up, but anyway I guess my question is more on the lines of how to go about doing parallel assignments in a loop)
for (x,i) in ([0,1,2],[3,4,5]):
# do something
why am I not allowed to do this in a for each loop (different list length)
for (x,i) in ([4,6,5,7,8,9],[1,2,3]):
# do something
I know you get a “ValueError: too many values to unpack”, but why doesn’t the loop stop when i is done with its iteration?
A real use of this would be for something like this that I was trying to do
for (keys,i) in (sorted(dic.keys(),key=custom_sort), range(10)):
print dic[keys]
where I’m sorting the dictionary as well as printing only the first 10 top results (assume the dictionary has hundreds of keys) – I only wanted the top 10 results.
Since this kind of syntax is not allowed anyway what could be the next best thing to do?
thanks
For this kind of stuff,
itertoolsis your friend.In your case,
itertools.islice()will do the trick:Alternatively, if you need the index as well, use
ziporitertools.izip: