I want to iterate over my list and do something with multiple elements, not just one element. I want to take the first element and some elements after it (they could be sequential or maybe the 3rd element from the one returned).
l = ['a', 'b', 'c', 'd', 'e']
for items in l:
print items[:3]
The output should be:
['a', 'b', 'c'], ['b', 'c', 'd'], ['c', 'd', 'e']
There are a lot of good answers, what if want to skip elements? Say, get an element, skip the next element, and get the 3rd element?
Output:
('a', 'c'), ('b','d'), ('c', 'e')
I guess enumerate is the best way to handle this?
Iterating through lists so simple and elegant I hoped similar syntax would allow you to use it inside a for loop on the element itself and not use range or enumerate.
l = ['a', 'b', 'c', 'd', 'e']
for items in l:
print (items[0], items[2])
(Yes, I know this code would give different results if the original list was a list containing lists. [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] would return [1, 3], [4, 6], [7, 9])
Use the izip() Function to Iterate Over Two Lists in Python It then zips or maps the elements of both lists together and returns an iterator object. It returns the elements of both lists mapped together according to their index.
l = ['a', 'b', 'c', 'd', 'e']
subarraysize = 3
for i in range(len(l)-subarraysize+1):
print l[i:i+subarraysize]
Output:
['a', 'b', 'c']
['b', 'c', 'd']
['c', 'd', 'e']
Not very Pythonic I know, but in its favour it does actually work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With