How does this for loop is work? [duplicate] - python

This question already has answers here:
for loops and iterating through lists - how does "for a[-1] in a:" work?
(3 answers)
Closed 6 years ago.
Please let me know how this for loop is working.
b= [4,5,6]
for b[-1] in b:
print(b[-1])
This code snippet is giving me output as:-
4
5
5
I checked it with Python 2.7

Each iteration, element i of b is picked. It is attributed to b[-1] (last element of b) and printed. So each step, the last element of b (6 before the loop) is attributed the value of the ith element.
Eventually, at the last iteration, the ith value is read and the value read is the value that was written the iteration before (that is, 5).
Modify the code to print b at each step and it becomes obvious:
b = [4,5,6]
for b[-1] in b:
print(b[-1])
print(b)
(Don't do this kind of things in real life.)

You can understand it while printing the whole b list:
b= [4,5,6]
for b[-1] in b:
print(b)
print(b[-1])
Output
[4, 5, 4] # first iteration, you set last element(6) with first element(4) [4,5,6] -> [4,5,4]
4
[4, 5, 5] # second iteration, you set last element(4) with element(5), [4,5,4] -> [4,5,5]
5
[4, 5, 5] # last iteration, you set last element(5) with element(5), no change
5
So basically every iteration your last element becomes the element you iterate with.

Related

Python for loop weird bug [duplicate]

This question already has answers here:
Why can I use a list index as an indexing variable in a for loop? [duplicate]
(6 answers)
Are for-loop name list expressions legal?
(2 answers)
Closed last year.
So in a quiz, I have given the question what the execution of this block of code gives (The one under).
a = [0, 1, 2, 3]
for a[0] in a:
print(a[0])
I had selected error but to my surprise, it actually works and is able to print all the elements inside the list. But how?
firstly the element getting variable (usually i) is shadowing the actual variable on top of that we are getting the first element inside a number so how is it working.
a[0] is type of a so it can be used to iterate over the array but as in look you are assigning value in a[0] it's value will change to last element of the array.
a = [0,1,2,3]
for a[0] in a:
print(a[0]
Will result in:
0
1
2
3
But now printing a will give you modified array:
print(a)
[3, 1, 2, 3]

I am trying the for statement to clear the list, but it fails. How is the for statement executed?

sum=[1,2,3,4,5,6,7,8,9]
for figure in sum:
print(list(sum))
print(figure)
sum.remove(min(sum))
print(figure)
print(list(sum))
print('\n')
print(list(sum))
You can't change the length of the iterable while iterating over it. If you want to print the minimum item and delete it until the list is empty, you should loop on the condition of the list beein empty, something like this:
sum=[1,2,3,4,5,6,7]
while sum:
print(min(sum))
sum.remove(min(sum))
output:
1
2
3
4
5
6
7
The problem of changing the iterable length is that python's interpreter basically will try to get the next element based on the previous position on the list.
For example, if you loop trough:
[a,b,c,d]
the first item will be a (the item on index 0). The next iteration of the for loop it will try to retrieve the item on index 1 but if you remove a, the ìndex 1 will not be b anymore, because your current list will look like this;
[b,c,d]
and the index 1is now c, skipping every other item on neext iterations
if you want to clear the whole list, the use the inbuilt function clear(). below is the example how to do that.
lis=[1,2,3,4,5,6,7,8,9]
print('printing original list',lis,sep=' : ')
# output printing original list : [1, 2, 3, 4, 5, 6, 7, 8, 9]
lis.clear()
print('printing new cleared list',lis,sep=' : ')
# output printing new cleared list : []

element modification during python list iteration [duplicate]

This question already has answers here:
Change value of currently iterated element in list
(3 answers)
Scope of python variable in for loop
(10 answers)
Closed 4 years ago.
Could anyone, please, explain what exactly happens in the following code to the "element" during iteration?
array = [2,3,4]
for element in array:
element = 3
print(array)
>>>[2, 3, 4]
Output is [2, 3, 4]
instead of [3, 3, 3]
Did I understand it correctly that when using "for element in l" syntax, we can only reference but not modify each element of an array of what does happen here?
P.S. I've seen the question named "why shouldn't you iterate like 'for element in array' ", but I couldn't find that one, so I asked it in this way. Seems like I found one of the disadvantages of iterating in this way. Please, redirect me to the mentioned question if possible.
Explanation
In the above example any changes to variable element in the loop is not possible.
Code
To get your expected output try this:
array = [2,3,4]
for i in range(len(array)):
array[i] = 3
print(array)
When the iteration start element variable already has the current value in the array. when you assign 3 to it it will contain it until the next iteration when it will again take the current value of the array and so on.
To get [3, 3, 3] you need to do it as the following:
array = [2,3,4]
for i in range(0,len(array)):
array[i]=3
print(array)
That's because element is a local variable in the scope of the for loop.
Run this snippet. I hope it can be self-explanatory (I used e instead of element), also I used enumerate to get the index:
array = [2,3,4]
for i, e in enumerate(array):
print('i =', i, 'e =', e)
e = 100
print('e = 100-->','e =', e, 'but array[i]=',array[i])
array[i] = e
print('array[i] = e --> array[i]=',array[i])
print('-'*10)
print(array) #=> [100,100,100]
Quick explanation
e and i are local variables which receive the value of the element and the index of the array at each iteration.
Inside the loop you can change the value of e but it doesn't affect the the array. To change the value inside the array it is required to access it by index (array[i]).

What does this Array split syntax means in python [duplicate]

This question already has answers here:
Understanding slicing
(38 answers)
Closed 5 years ago.
(X_train, X_test) = X[50:], X[:50]
How does the split happens here? Please provide the inner explanation.
Take the following example on a simple list:
a = [0, 1, 2, 3, 4, 5, 6, 7]
print(a[:3])
print(a[3:])
Will output
[0, 1, 2]
# [:3] returns everything from the start, to before the third index
[3, 4, 5, 6, 7]
# [3:] returns everything from the third index to the end
Expanded to [50:] and [:50] will return everything from the 50th index to the end and everything from the beginning to before the 50th index respectively.
The second part of your question is about tuple unpacking. If there are the same number of variables to set as there are elements in some collection such as a tuple or list, it'll unpack them. For example:
(a, b) = 42, 9001
print("Val A:", a)
print("Val B:", b)
Will output:
Val A: 42
Val B: 9001
You actually don't even need the () brackets around the variables.
Expanded to your question, it's actually just a simplified, one line version of saying:
X_train = X[50:]
X_test = X[:50]
Assuming X is a list, tuple or an array, the first slice ([50:]) will return all the elements from the 50th element to the end. The second slice ([:50]) will return the first through the 49th element.

Why does calling the list constructor twice result in an empty list? [duplicate]

This question already has an answer here:
Calling list() twice on reversed() returns an empty list the second time
(1 answer)
Closed 7 years ago.
I am learning python now and I met a question I don't know why
>>> a = [1,2,3,4]
>>> b = reversed(a)
>>> list(b)
[4, 3, 2, 1]
>>> list(b)
[]
Why the second time I called list(b) it returned an empty list
The reason is that b is not the reversed list itself, but a listreverseiterator. So when you call list() the first time, it iterates over b and creates a new list from the items output from that iterator. When you do it a second time, b is still the original iterator and has already gone through all the items, so it doesn't iterate over anything, resulting in an empty list

Categories

Resources