+ 5

Python: How should we interpret this for loop?

arr = ['b','c','d'] # a list called arr x={1:'a'} # a dictionary called x n = 1 for x[n] in arr: # what is going on here? n+=1 # What if there is no such thing as x[2], x[3], x[4] etc... ? print(x) # outputs {1: 'b', 2: 'c', 3: 'd'} From my understanding, x[n] refers to the dictionary's n key, which is string 'a'. What does for x[n] in arr (or for 'a' in arr) mean? Is this analogous to: for i in ['b','c','d'] where i is an an arbitrary letter to denote "item in list"? Referring to line n+=1 I also don't understand what happens if there are no such thing as x[2], x[3], x[4] etc... After all, the dictionary only has one key:value pair...

16th Sep 2020, 8:10 PM
Solus
Solus - avatar
1 Odpowiedź
+ 5
This is a simple process of assigning a dictionary! ===== for x[n] in arr: n+=1 ===== Here, The for loop runs 3 times (the length of the list) Now, First loop, for x[n] means we are defining a variable x[n] (ohh no, it is already declared, but wait, let's override it) So, x[n] will change to the first element of the arr! Here, n = 1 So, x becomes {1:'b'} Now, n is incremented by 1 So, x[n] is same as x[2] (wow, a new variable to be declared) So, it will get assigned to the second element of the list (because we are in the second loop) Then the same process for 'd'. More to know: Remove that n+=1 And you will see, x is {1:'d'} Because, we are not using a new variable for the new loops and it is getting overriden again and again! For example, for i in [1,2,3]: pass print(i) And you will see, i = 3 (overridden again and again) Similarly, x = [0,0,0,0,0] i = 0 arr = [1,2,3,4,5] for x[i] in arr: i+=1 print(x) Output: [1,2,3,4,5]
16th Sep 2020, 8:39 PM
Namit Jain
Namit Jain - avatar