Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic loops--how to get multiple elements while iterating a list

Tags:

python

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])

like image 763
Jason Wirth Avatar asked Mar 13 '11 20:03

Jason Wirth


People also ask

How do I iterate two lists at the same time in Python?

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.


Video Answer


1 Answers

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.

like image 59
David Heffernan Avatar answered Oct 19 '22 23:10

David Heffernan