Make App Pie

Training for Developers and Artists

From Apple to Raspberry Pie: Python For Loops

appleberryPython for loops is, loopy.

C, Objective-C, Java and most other languages use a for loop that is numerical.


for (int i=0; i<5;i++){
     NSLog(@"The index is: %i", i);
}

This code will count the numbers, and when the numbers are greater than 5, will stop. Python is different. The for loop is more like fast enumeration in Objective-C than a counting loop.  Python lists individual elements in sequene from some collection such as an array or list.  A closer objective-C example might be:

NSArray *array = [NSArray arrayWithObjects:@"foo", @"bar", nil]; for(NSString *myString in array) { NSLog(myString); }

and Python codes as:

array = ["foo", "bar"]
for my_string in array {
    print(my_string)
}

Now look at this  same example, except I’ve added a real number and an integer

array = [&quot;foo&quot;, &quot;bar&quot;, 3.1415926, 1]
for my_string in array {
    print(my_string)
}

While it might make Xcode cringe in warnings and errors, this actually runs in Python without a hitch. Dynamic typing at its best. The for loop doesn’t care about the type.

Often we don’t want the element in the array. We want a number, which is easy with C-style for loops. Python has a solution to this: the range() function. The range() function sets a range of integers to enumerate through. there are one , two and three parameter varieties.

range(5)   # range of 0 through 4
range(1,5) #range of 1 through 4
range (1,20,2) #range of 1 through 19  stepping by 2

We replace the array or list with range in the for loop, and we get something similar to our C-style loop


# for (int i=0; i<5; i++){}
for i in range(5):
    print ('Simple for ', i)

# for (int i=1; i<5; i++){NSLog(@"Simple for from 1 %i",i);}
for i in range(1,5):
    print ('Simple for from 1 ', i)

# for (int i=1; i<20; i+=2){NSLog(@"Simple for from 1 %i",i);}
for i in range(1,20,2):
    print ('For from 1 by 2 ', i)

Note in each of these examples our test expression in the C-style loop is i< 5 not i<= 5. You count to a number less than the number in the second parameter.

Once you understand the range() function in for loops, they become easy. One last example. What if you wanted both an index and the value of its index?

a=['Mary','had','a','little','lamb']

for i in range(len(a)):
    print (i, a[i])
    a[i] = a[i] + '!!!'

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: