Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing elements with offsets in Python's for .. in loops

Tags:

python

loops

I've been mucking around a bit with Python, and I've gathered that it's usually better (or 'pythonic') to use

for x in SomeArray:

rather than the more C-style

for i in range(0, len(SomeArray)):

I do see the benefits in this, mainly cleaner code, and the ability to use the nice map() and related functions. However, I am quite often faced with the situation where I would like to simultaneously access elements of varying offsets in the array. For example, I might want to add the current element to the element two steps behind it. Is there a way to do this without resorting to explicit indices?

like image 366
int3 Avatar asked Aug 15 '09 12:08

int3


People also ask

How do you access items from a for loop in Python?

Use the python enumerate() function to access the index in for loop. enumerate() method is an in-built method in Python, which is a good choice when you want to access both the items and the indices of a list. enumerate() method is the most efficient method for accessing the index in a for loop.

Can we access the elements of a set using while loop in Python?

You cannot access items in a set by referring to an index, since sets are unordered the items has no index. But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.


2 Answers

The way to do this in Python is:

for i, x in enumerate(SomeArray):
    print i, x

The enumerate generator produces a sequence of 2-tuples, each containing the array index and the element.

like image 106
Greg Hewgill Avatar answered Sep 19 '22 05:09

Greg Hewgill


List indexing and zip() are your friends.

Here's my answer for your more specific question:

I might want to add the current element to the element two steps behind it. Is there a way to do this without resorting to explicit indices?

arr = range(10)
[i+j for i,j in zip(arr[:-2], arr[2:])]

You can also use the module numpy if you intend to work on numerical arrays. For example, the above code can be more elegantly written as:

import numpy
narr = numpy.arange(10)
narr[:-2] + narr[2:]

Adding the nth element to the (n-2)th element is equivalent to adding the mth element to the (m+2) element (for the mathematically inclined, we performed the substitution n->m+2). The range of n is [2, len(arr)) and the range of m is [0, len(arr)-2). Note the brackets and parenthesis. The elements from 0 to len(arr)-3 (you exclude the last two elements) is indexed as [:-2] while elements from 2 to len(arr)-1 (you exclude the first two elements) is indexed as [2:].

I assume that you already know list comprehensions.

like image 32
Christian Alis Avatar answered Sep 22 '22 05:09

Christian Alis