What is the variable "i" in loops? [duplicate] - python

This question already has answers here:
Scope of python variable in for loop
(10 answers)
Changing iteration variable inside for loop in Python [duplicate]
(6 answers)
Closed 2 years ago.
I saw the following code in a coding challenge, I don't know why it returns 3, but check the code and tell me what do u think.
myList = [1,2,3,4]
for i in myList:
i += 1
print(myList[-2])
When I saw the code I said it will print 4 because in the loop we added 1 in all integers in the list, and [-2] is supposed to give me the second-last value, which is 4 according to what I think.
I know I'm missing something here but I don't know what it is, so if anyone could explain this to me I'll appreciate it. Probably I'm not understanding i, I'm not sure.

Explanation
The line:
for i in myList
Iterates over the items of the list myList, not it's indices.
The line in it that adds one i += 1 doesn't assign the new value to the list, therefore is unchanged.
How to Fix
However, if we change the code to iterate over the indices:
for i in range(len(myList))
We can now change the values in the list:
myList[i] += 1
Code fix:
myList = [1,2,3,4]
for i in range(len(myList)):
myList[i] += 1
# 4
print(myList[-2])
Some Advice
It's a convenience in Python to name variables with lower-case, underscore separated names.
So myList would be my_list.
It doesn't change how the program behaves but would be more readable for your future teammates.

Your reasoning is ok, but note that the changed value is not stored back to the list replacing the original (the list remains unchanged!)

The index of list is
myList = [1, 2, 3, 4]
+ve index 0 1 2 3
-ve index -4 -3 -2 -1
i is modified in that iteration and is not stored in list. Hence myList[-2] is 3

i is the current item of your list, i took the value but not is a reference, therefore is unchanged

Related

Can someone explain logic behind this python code

This python code is giving certain output someone please explain logic behind it.
l = [1,2,3,4,5]
for l[-1] in l:
print(l[-1])
output for this code is
1
2
3
4
4
You iterate through the list while assigning each value to the last value of list instead of the temporary i that we always use. So you can print every value of list except the last one cause second last one overwrites it and that's why the second last is printed twice.
Now understand for-loop behaviour in python. lets consider the following for loop:
for {val} in l: #curly braces only for the post, please do not write in python
print(val)
What python does is launch an iterator over the list l, and for every value in the list, the variable in the {} is assigned the value and prints it -> 1 2 3 4 5
now what has happened in your code is the {} contain a reference, to the iterating list itself, specifically to -1 index of the list, aka, the last element
so the for-loop still does the exact same thing, goes over the list from left to right, but also assigns the value to the last position of the same list it is iteration over.
DRY RUN:
outside for-loop: l= [1,2,3,4,5]
iteration 1: l= [1,2,3,4,1]
iteration 2: l= [1,2,3,4,2]
iteration 3: l= [1,2,3,4,3]
iteration 4: l= [1,2,3,4,4]
now for last iteration, it is iterating over and assigning to the same position, so it outputs 4 again.
TLDR:
instead of using a temp variable in the for loop, we are using a postion in our list itself, and actually modifying it as a result every iteration.

I have written a program to create a list that stores the intersection of two lists. It's showing an error at line 23 [duplicate]

This question already has answers here:
Why does this iterative list-growing code give IndexError: list assignment index out of range? How can I repeatedly add (append) elements to a list?
(9 answers)
Closed 9 months ago.
I'm using an algorithm similar to Merge Sort. Firstly, I'm sorting both the lists. Then, I'm comparing the first element of each sorted list, and adding the smaller element to another list. Here's my code:
leftList=[int (x) for x in input().split()]
rightList=[int (x) for x in input().split()]
output=[]
# print(leftList,rightList)
leftList.sort()
rightList.sort()
# print(leftList,rightList)
i=j=k=0
# Until we reach the end of either leftList or rightList, pick the smaller of
# leftList[i] and rightList[j], and place it in the correct position in output[]
while i<len(leftList) and j<len(rightList):
if leftList[i]<=rightList[j]:
output[k]=leftList[i]
i+=1
else:
output[k]=rightList[j]
j+=1
k+=1
# When we run out of elements in either leftList or rightList,
# place the remaining elements in output[]
while i<len(leftList):
output[k]=leftList[i]
i+=1
k+=1
while j<len(rightList):
output[k]=rightList[j]
j+=1
k+=1
print(output)
Here's the error that I'm getting:
---> 23 output[k]=rightList[j]
IndexError: list assignment index out of range
Please help!
In python, you can't set a list value you haven't initialised as you can in other languages. This means that, if I do something like mylist[3] = 4, the length of mylist must be at least 4 before the assignment, and the assignment can't make some slots magically appear.
So, instead of incrementing a k counter, just replace all occurences of output[k] = ... with output.append(...).
Your problem is at this line:
output[k]=rightList[j]
Your list is empty and cannot access the first element. The best way to insert would be the append method:
output.append(rightList[j])

did I did something wrong with list and for loop in python? [duplicate]

This question already has answers here:
Why does this iterative list-growing code give IndexError: list assignment index out of range? How can I repeatedly add (append) elements to a list?
(9 answers)
Closed 1 year ago.
the thing that I am supposed to do is,
get 10 int
find the different value after doing %42 for those 10 input int
and what I thought is, like this
n = []
for i in range(10):
a = int(input())
n[i] = a%42
s = set(n)
print(len(s))
but it didn't work with a message of
----> 4 n[i] = a%42
IndexError: list assignment index out of range
and by googling I have solved this question by adding append.
n = []
for i in range(10):
a = int(input())
print("a",a)
b = a%42
print("b",b)
n.append(b)
s = set(n)
print(len(s))
** here is my question. why did my code didn't work? I thought my method's logic is solid. Is there some knowledge that I am missing about? **
thank you previously.
actually when you were trying first way you were using lists built-in dunder(magic method) which asks that there must be an element at that index before changing its value, meanwhile list is empty and hence it can't find an element whose value has to be chanced but append works something like this:
yourList += [newElement]
which is basically like list concatination.
Your code doesn't work because n is an empty list so it has no sense to assign a value to an index.
If you know the size of your list you can do:
# this works
n = [size]
n[0] = 1

When iterating through a list in python, how can I get the current number of "i"? [duplicate]

This question already has answers here:
Accessing the index in 'for' loops
(26 answers)
Closed 8 years ago.
I have a list and am iteratively performing a function on each item. I am trying to print out how far through the iteration the script is. The problem is that I can't easily get the position.
Here is what I have so far, but it generates a ValueError: 'item' is not in list.:
that_number = len(mylist)
for i in mylist:
this_number = mylist.index(i)
print this_number, " out of ", that_number
DO SOMETHING
print "Done!"
I am aiming for the output:
1 out of 3
2 out of 3
3 out of 3
Done!
This question is related in that it is trying to find the position in a list, however is there a valid way of getting the element position without using enumerate?
the enumerate() function really gives you what you want. For other ways to do it though, you can do a for loop over a range:
for i in range(len(myList)):
print myList[i], "at index", i
range(len(myList)) creates a list from 0 to len(myList) - 1 so you can use that to index into each element of the list.
Use a Generator Instead
For long lists creating another list the size of your original to loop over may be undesirable. Here is the same code as above for both python2 and 3 which will execute a for loop over a generator instead of a list.
Python 2
For Python 2, just use xrange instead of range:
for i in xrange(len(myList)):
print myList[i], "at index", i
Python 3
For Python 3 range returns a generator, so lets just change the print statement:
for i in range(len(myList)):
print(myList[i], "at index", i)
mmm, you'll have issue with duplicates on your list. If it's only for debugging/display purposes
that_number = len(mylist)
this_number=0
for i in mylist:
this_number+=1
print this_number, " out of ", that_number
DO SOMETHING
print "Done!"
how would you deal with a list containing [1,2,3,2,1] ?

Don't go to next iteration in for loop [duplicate]

This question already has answers here:
repeat an iteration of for loop
(4 answers)
Closed 8 years ago.
Not sure if this is possible, mostly a curiosity question although I may have a case where this may be useful. Basically I'm wondering if it's possible to not go to the next iteration in a loop, and instead try repeating that iteration. For example:
myList = ['a','b','c']
for thing in myList:
if something:
continue
else:
try again (same iteration)
Is what I'm asking for clear? A way I've seen of doing this is to use a while loop operating only on the first element of a list and then continuously deleting the first element of the list if some condition is met.
Thanks
You can use a while loop and manually substract from the iteration variable. Demo:
import time
myList = [1,2,3,4,5,6,7,8]
i = 0
while i < len(myList):
time.sleep(1)
print(i)
if i == 3:
i -= 1
i += 1
Of course, you'll need to access your thing by indexing into myList now, i.e. do something to/with myList[i].

Categories