for loop in python for beginners part - 2

Example 3
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
list1 = [1,2,3,4,5,6,7,8,9,10]
for num in list1:
list_sum = list_sum + sum
print(list_sum)
OUTPUT
55
Example 4
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 a string':
print(letter)
OUTPUT
T
h
i
s
i
s
a
s
t
r
i
n
g
Example 5
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 6
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 that many objects will deliver their iterables through tuples. Let's start exploring iterating through Dictionaries to explore this further!
Example 7
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 returns 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:
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.
Post a Comment
Post a Comment
if you have any doubts, please let me know