[Tutor] Traversing lists or getting the element you want.

Steven D'Aprano steve at pearwood.info
Mon Feb 3 01:57:15 CET 2014


On Sun, Feb 02, 2014 at 02:46:38PM -0600, Kipton Moravec wrote:
> I am new to Python, and I do not know how to traverse lists like I
> traverse arrays in C.

You can do this, but normally shouldn't:

data = [2, 4, 8, 16, 32]
for i in range(0, len(data)):
    x = data[i]
    print(x)


That is a more-or-less exact translation of what you might do in a 
language like C or Pascal. But in Python, it's not considered good form. 
(Although, if you are doing a direct translation of some C code, it 
might be acceptable.) Instead, you should iterate directly over the 
elements of the list:

data = [2, 4, 8, 16, 32]
for x in data:
    print(x)


(Python's for-loop is what some other languages call "for-each".) If you 
need the index as well, you can do this:

data = [2, 4, 8, 16, 32]
for i, x in enumerate(data):
    print(i, x)


The rest of your question seems pretty interesting, unfortunately I 
don't have time to get into it now. Good luck!

-- 
Steven


More information about the Tutor mailing list