Python For Loop

Updated: Aug 21, 2020



Now we will study about loops in python. What if you want to execute a code until a specific condition holds true ? Here you will have to use loops in python.


A for loop acts as an iterator in Python; it goes through items that are in a sequence or any other itearble item. Objects that we can iterate over include strings, lists, tuples, and even built-in iterables for dictionaries, such as keys or values.


Here's the general format for a for loop in Python:



  for item in object:    
    statements to do stuff
    

The variable name used for the item is completely up to the coder, so use your best judgment for choosing a name that makes sense and you will be able to understand when revisiting your code. This item name can then be referenced inside your loop, for example if you wanted to use if statements to perform checks.


Let's go ahead and work through several example of for loops using a variety of data object types


Example 1


Iterating through a list


# We'll learn how to automate this sort of list in the next lecture
list1=[1,2,3,4,5,6,7,8,9,10]
for num in list1:
       print(num)
       

Output:-



1
2
3
4
5
6
7
8
9
10



Example 2


Another common idea during a for loop is keeping some sort of running tally during multiple loops. For example, let's create a for loop that sums up the list:



# Start sum at zero
list_sum = 0 

for num in list1:
    list_sum = list_sum + num

print(list_sum)

Output:-




55



Example 3


We've used for loops with lists, how about with strings? Remember strings are a sequence so when we iterate through them we will be accessing each item in that string



    for letter in 'This is  LinuxAdvise':
     print(letter)
    

Output:-


T
h
i
s

i
s

L
i
n
u
x
A
d
v
i
s
e


Example 4


Let's now look at how a for loop can be used with a tuple:


tup = (1,2,3,4,5)
for t in tup:
    print(t)

Output:-



1
2
3
4
5



Example 5


Tuples have a special quality when it comes to for loops. If you are iterating through a sequence that contains tuples, the item can actually be the tuple itself, this is an example of tuple unpacking. During the for loop we will be unpacking the tuple inside of a sequence and we can access the individual items inside that tuple!



list2 = [(2,4),(6,8),(10,12)]
for tup in list2:
    print(tup)
    

Output:-



(2, 4)
(6, 8)
(10, 12)




# Now with unpacking!
for (t1,t2) in list2:
    print(t1)

Output:-



2
6
10



Cool! With tuples in a sequence we can access the items inside of them through unpacking! The reason this is important is because many objects will deliver their iterables through tuples. Let's start exploring iterating through Dictionaries to explore this further!


Example 6



d={'k1':1,'k2':2,'k3':3}
for item in d:
    print(item)
 

Output:-



k1
k2
k3



Notice how this produces only the keys. So how can we get the values? Or both the keys and the values?


We're going to introduce three new Dictionary methods: .keys(), .values() and .items()


In Python each of these methods return a dictionary view object. It supports operations like membership test and iteration, but its contents are not independent of the original dictionary – it is only a view. Let's see it in action:


# Create a dictionary view object
print(d.items())

output:-


dict_items([('k1', 1), ('k2', 2), ('k3', 3)])

Since the .items() method supports iteration, we can perform dictionary unpacking to separate keys and values just as we did in the previous examples.



# Dictionary unpacking
for k,v in d.items():
    print(k)
    print(v)
    

output:-



k1
1
k2
2
k3
3



If you want to obtain a true list of keys, values, or key/value tuples, you can cast the view as a list:



 
d={'k1':1,'k2':2,'k3':3}
# Dictionary unpacking
for k,v in d.items():
    list(d.keys())
print(list(d.keys()))
   

Output:-



  ['k1', 'k2', 'k3']



Remember that dictionaries are unordered, and that keys and values come back in arbitrary order. You can obtain a sorted list using sorted():



print(sorted(d.values()))

Output:-



[1, 2, 3]



Conclusion


We've learned how to use for loops to iterate through tuples, lists, strings, and dictionaries. It will be an important tool for us, so make sure you know it well and understood the above examples.




20 views0 comments

Recent Posts

See All
 

Subscribe Form

©2020 by Linux Advise