Reputation: 970
how can I retrieve 2 items from a loop at a time?
I have this list
lst = ['url1', 'value1', 'url2', 'value2', ... ]
I want to loop it and for every iteration I want to fetch 2 items.
for x in lst:
x # here x loops 1 by one.
I am using bellow solution
for i in range(0, len(lst), 2):
url = lst[i]
val = lst[i+1]
I wan to know is there anything built in?
Upvotes: 1
Views: 136
Reputation: 336128
>>> lst = ['url1', 'value1', 'url2', 'value2']
>>> i = iter(lst)
>>> zip(i,i)
[('url1', 'value1'), ('url2', 'value2')]
or, probably more useful:
>>> i = iter(lst)
>>> dict(zip(i,i))
{'url1': 'value1', 'url2': 'value2'}
Upvotes: 9