Command to select the next tuple in the list

I was wondering if there are any commands for automatically selecting the next element in a tuple without having to enter it?

eg.

nul = 0 noofvalue = 5 value = ['a', 'b', 'c', 'd', 'e'] for nul < noofvalue: file.write(value[0]) 

which command can I use here to add 1 to the β€œvalue”, so when the file loops use the value [1] instead of using the value [0]?

 nul = nul + 1 

I searched the answer for the search and searched, but I don’t understand what they are talking about, since I am very new to computer coding, so please forgive my ignorance.

+4
source share
3 answers

I think you want enumerate() . I will add my own example, since your example is a bit strange:

 >>> L = ['a', 'b', 'c', 'd', 'e'] >>> for index, value in enumerate(L): ... try: ... print L[index+1] # Prints the next item in the list ... except IndexError: ... print 'End of the list!' ... b c d e End of the list! 
+3
source

In Python, you can iterate over a list or tuple in the same way:

 for x in value: do_something(x) 
+1
source

The first value = ['a', 'b', 'c', 'd', 'e'] not tuple , this is list . In Python, to iterate a for loop, you can simply do:

 for v in value: print v # file.write(v) 

(I think you have a C-background where we need an index to access the elements and iterate over the arrays).

if you want to index, also use the `enumerate (any_sequence) function, which returns pairs (index, value) in the list,

 >>> list(enumerate(value)) [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')] 

so you can:

 for i, v in enumerate(value): print i, v 

Of course, if you want to explicitly use the index, follow these steps:

 index = 0 for v in value: print index, v index += 1 

but this is not a Pythonic path, therefore not preferable in genral.

0
source

All Articles