Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating for loop until list.length

Tags:

I'm reading about for loops right now, and I am curious if it's possible to do a for loop in Python like in Java.

Is it even possible to do something like

for (int i = 1; i < list.length; i++) 

and can you do another for loop inside this for loop ?

Thanks

like image 417
Agape Avatar asked Jan 26 '13 01:01

Agape


People also ask

How do I iterate over a list length?

You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes.

Does a for loop create a list?

You can use a for loop to create a list of elements in three steps: Instantiate an empty list. Loop over an iterable or range of elements. Append each element to the end of the list.

How do I add a list to a for loop?

Use the append() method to add elements to a list while iterating over the list. Means you can add item in the list using loop and append method.


1 Answers

In Python you can iterate over the list itself:

for item in my_list:    #do something with item 

or to use indices you can use xrange():

for i in xrange(1,len(my_list)):    #as indexes start at zero so you                                      #may have to use xrange(len(my_list))     #do something here my_list[i] 

There's another built-in function called enumerate(), which returns both item and index:

for index,item in enumerate(my_list):     # do something here 

examples:

In [117]: my_lis=list('foobar')  In [118]: my_lis Out[118]: ['f', 'o', 'o', 'b', 'a', 'r']  In [119]: for item in my_lis:     print item    .....:      f o o b a r  In [120]: for i in xrange(len(my_lis)):     print my_lis[i]    .....:      f o o b a r  In [122]: for index,item in enumerate(my_lis):     print index,'-->',item    .....:      0 --> f 1 --> o 2 --> o 3 --> b 4 --> a 5 --> r 
like image 171
Ashwini Chaudhary Avatar answered Oct 30 '22 14:10

Ashwini Chaudhary