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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With