I am using python 2.7. I am trying to simulate popping of element from a list using the pop function. But I'm getting an inconsistent result.
Code using a variable list
list_pop = [1,2,3]
for x in list_pop:
print list_pop
y = list_pop.pop(0)
print y
Result:
[1, 2, 3]
1
[2, 3]
2
Code without using variable to hold the list
list_pop = [1,2,3]
for x in [1,2,3]:
print list_pop
y = list_pop.pop(0)
print y
[1, 2, 3]
1
[2, 3]
2
[3]
3
I have tried popping index 0 from a list with one element it's working. I'm wondering why my first code halts printing after number 2 but when I print the list_pop it gives [3] the first code should still iterate through it and print 3. I'm expecting same results for both code. What am I missing here?
In the first case, you are iterating over the list while modifying it, which will almost certainly give you unexpected results.
In the second case, you are not iterating over the same list you are changing, so the result is a fixed number of iterations.
If you wanted to do the first one and examine all elements, a while loop may work better.
while not len(list_pop) == 0:
print list_pop
y = list_pop.pop(0)
print y
Another alternative is to make a copy of the list and iterate over the copy:
for x in list_pop[:]:
print list_pop
y = list_pop.pop(0)
print y
A good general rule to follow is that you shouldn't modify a list that you are iterating over. This is exactly the behavior you should get: the list you are iterating over gets smaller and smaller, so the loop will have fewer and fewer items to iterate over. It doesn't iterate over the original list, it iterates over the current list.
In the second example you iterate over a list that never changes, so you get exactly three iterations.
You might want to take a look at this question: Remove items from a list while iterating
You should not modify your list while looping through it. That's why the results are inconsistent. Instead you can use a while loop and check is list empty:
while list_pop:
print list_pop
y = list_pop.pop(0)
print y
Related
I've had a look through the forums and can't find anything to do with multiplying all elements in an array recursively.
I've created the following code that almost does what I want. The goal is to use no loops and only recursion.
Here's the code:
def multAll(k,A):
multAllAux(k,A)
return A[:]
def multAllAux(k,A):
B = [0]
if A == []:
return 0
else:
B[0] = (A[0] * k)
B.append(multAllAux(k,A[1:]))
return B
print(multAllAux(10, [5,12,31,7,25] ))
The current output is:
[50, [120, [310, [70, [250, 0]]]]]
However, it should be:
[50,120,310,70,250]
I know I am close, but I am at a complete loss at this point. The restrictions of no loops and solely recursion has left me boggled!
Your multAllAux function returns a list. If you append a list to another list, you get this nested list kind of structure that you are getting right now.
If you instead use the "extend" function; it will work as expected.
>>> a = [1, 2, 3]
>>> a.extend([4, 5])
>>> a
[1, 2, 3, 4, 5]
extend takes the elements from a second list and adds them to the first list, instead of adding the second list itself which is what append does!
Your function also returns a zero at the end of the list, which you don't need. You can try this:
def mult(k, A: list) -> list:
return [k * A[0]] + mult(k, A[1:]) if A else []
The problem is here:
B.append(multAllAux(k,A[1:])))
What .append(..) does is it takes the argument, considers it as a single element and adds that element to the end of the list. What you want is to concatenate to the list (ie the item being added should be seen as a list of elements rather than one single element).
You can say something like: B = B + multAllAux(..) or just use +=
B += multAllAux(...)
BTW, if you wanted to multiply a single number to a list, there is a very similar construct: map(..). Note that this behaves slightly differently depending on whether you're using Py2 or Py3.
print(map(lambda x: x * 10, [5,12,31,7,25]))
I am trying to perform in-place modification of a list of list on the level of the primary list. However, when I try to modify the iterating variable (row in the example below), it appears to create a new pointer to it rather than modifying it.
Smallest example of my problem.
c = [1,2,3]
for x in c:
x = x + 3
print(c) #returns [1,2,3], expected [4,5,6]
The above example is a trivial example of my problem. Is there a way to modify x elementwise, in-place and have the changes appear in C?
Less trivial example of my problem. I am switching all 0's to 1's and vice-versa.
A = [[1,1,0],
[1,0,1],
[0,0,0]]
for row in A:
row = list(map(lambda val: 1 - val, row))
print(A)
Expected
A = [[0,0,1],
[0,1,0],
[1,1,1]]
Returned
A = [[1,1,0],
[1,0,1],
[0,0,0]]
update:
Great answers so far. I am interested how the iterating variable (row in the second example) is linked to the iterable variable (A in the second example).
If I do the following, which reverses each sublist of A, it works perfectly.
Why does the following example, where I modify the iterating variable works but the above examples do not?
A = [[1,1,0],
[1,0,1],
[0,0,0]]
for row in A:
row.reverse()
print(A)
#returns, as expected
A = [[0, 1, 1],
[1, 0, 1],
[0, 0, 0]]
I found this in the docs: https://docs.python.org/3/tutorial/controlflow.html#for
Python’s for statement iterates over the items of any sequence (a list
or a string), in the order that they appear in the sequence.
If you need to modify the sequence you are iterating over while inside
the loop (for example to duplicate selected items), it is recommended
that you first make a copy. Iterating over a sequence does not
implicitly make a copy.
I was wrong in my first response, when iterating through a list it returns the actual items in that list. However, it seems they cannot be edited directly while they are being iterated through. This is why iterating through the integers the length of the list works.
As for why the .reverse() function works, I think it's because it is affecting a list instead of a value. I tried to use similar built in functions on nonlist datatypes like .replace() on strings and it had no effect.
All of the other list functions I tried worked: .append(), .remove(), and .reverse() as you showed. I'm not sure why this is, but I hope it clears up what you can do in for loops a bit more.
Answer to old question below:
The way you are using the for loops doesn't affect the actual list, just the temporary variable that is iterating through the list. There are a few ways you can fix this. Instead of iterating through each element you can can count up to the length of the list and modify the list directly.
c = [1,2,3]
for n in range(len(c)):
c[n] += 3
print(c)
You can also use the enumerate() function to iterate through both a counter and list items.
c = [1,2,3]
for n, x in enumerate(c):
c[n] = x + 3
print(c)
In this case, n is a counter and x is the item in the list.
Finally, you can use list comprehension to generate a new list with desired differences in one line.
c = [1, 2, 3]
d = [x + 3 for x in c]
print(d)
The usual way to poke values into an existing list in Python is to use enumerate which lets you iterate over both the indices and the values at once -- then use the indices to manipulate the list:
c = [1,2,3]
for index, value in enumerate(c):
c[index] = value + 3
For your second example you'd do almost the same:
A = [[1,1,0],
[1,0,1],
[0,0,0]]
for row in A:
for index, val in row:
row[index] = 0 if val > 0 else 1
In the second example the list objects in A become the loop variable row -- and since you're only mutating them (not assigning to them) you don't need enumerate and the index
If you want to keep it consice without creating an additional variable, you could also do:
c = [1,2,3]
print(id(c))
c[:] = [i+3 for i in c]
print(c, id(c))
Output:
2881750110600
[4, 5, 6] 2881750110600
Using list comprehension here also will work:
A = [[1,1,0],
[1,0,1],
[0,0,0]]
A = [[0 if x > 0 else 1 for x in row] for row in A]
print(A)
Output:
[[0, 0, 1],
[0, 1, 0],
[1, 1, 1]]
Here is what I exactly want:
A = [1,2,3]
for a in A:
if a > 1:
del a
print(A)
I want list a to be [1], however it will still be [1,2,3].
So my real goal is to delete current element I get now.
I know there is one usage of 'del' liking this:
A = [1,2,3]
for i, a in enumerate(A):
if a > 1:
del A[i]
print(A)
and list a will be [1,3] but not [1].
Because when I use
del a[1] #2
the orginally 3 in list A will be needed to use index 1 to get it from list A rather than using 2. So I can not delete it successfully.
How can I delete the current element in the list?
It is almost never a good idea to change a collection you are iterative over. In many cases, a better way would be to select only these elements that you want in your new list.
A pythonesque way to do this is using list comprehension:
a = [1,2,3]
b = [x for x in a if x <= 1]
print (b)
the '[ .. for ... if ..]' is a very nice syntax for all kinds of list operations like map and filter.
Notice that I complemented your filter predicate, because I select what has to stay, in stead of what has to be deleted.
Hope this helps!!
B = filter(lambda x: x <= 1, A)
Then B is all elements that less than or equal 1 of A.
In general, you must be very careful while modifying the data structure if you are currently iterating over its elements. Python will give you an error if you try to delete elements from a list while iterating over the elements of the list. If you really want to modify the list, then use a different iteration strategy, e.g.
A = [1, 2, 3, 1, 2, 3]
n = len(A)
i = 0
while i < n:
if A[i] > 1:
del A[i]
n -= 1
else:
i += 1
print(A)
This is one way to get the result you want.
>>> [i for i in [1,2,3] if i<=1]
[1]
>>> list(filter(lambda x:x<=1, [1,2,3]))
[1]
>>>
all list elements that are >1 are filtered out
In your Code when you are trying to delete the value
del a
You actually were trying to delete a temporary variable a whose value is same as the value of A[X] . So the value in A still remains unaffected. If you want to delete the value from A, you can make use of
del A[X]
a.remove(value)
these methods will delete/remove the value from the List .
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 4 months ago.
This is such a simple issue that I don't know what I'm doing wrong. Basically I want to iterate through the items in an empty list and increase each one according to some criteria. This is an example of what I'm trying to do:
list1 = []
for i in range(5):
list1[i] = list1[i] + 2*i
This fails with an list index out of range error and I'm stuck. The expected result (what I'm aiming at) would be a list with values:
[0, 2, 4, 6, 8]
Just to be more clear: I'm not after producing that particular list. The question is about how can I modify items of an empty list in a recursive way. As gnibbler showed below, initializing the list was the answer. Cheers.
Ruby (for example) lets you assign items beyond the end of the list. Python doesn't - you would have to initialise list1 like this
list1 = [0] * 5
So when doing this you are actually using i so you can just do your math to i and just set it to do that. there is no need to try and do the math to what is going to be in the list when you already have i. So just do list comprehension:
list1 = [2*i for i in range(5)]
Since you say that it is more complex, just don't use list comprehension, edit your for loop as such:
for i in range(5):
x = 2*i
list1[i] = x
This way you can keep doing things until you finally have the outcome you want, store it in a variable, and set it accordingly! You could also do list1.append(x), which I actually prefer because it will work with any list even if it's not in order like a list made with range
Edit: Since you want to be able to manipulate the array like you do, I would suggest using numpy! There is this great thing called vectorize so you can actually apply a function to a 1D array:
import numpy as np
list1 = range(5)
def my_func(x):
y = x * 2
vfunc = np.vectorize(my_func)
vfunc(list1)
>>> array([0, 2, 4, 6, 8])
I would advise only using this for more complex functions, because you can use numpy broadcasting for easy things like multiplying by two.
Your list is empty, so when you try to read an element of the list (right hand side of this line)
list1[i] = list1[i] + 2*i
it doesn't exist, so you get the error message.
You may also wish to consider using numpy. The multiplication operation is overloaded to be performed on each element of the array. Depending on the size of your list and the operations you plan to perform on it, using numpy very well may be the most efficient approach.
Example:
>>> import numpy
>>> 2 * numpy.arange(5)
array([0, 2, 4, 6, 8])
I would instead write
for i in range(5):
list1.append(2*i)
Yet another way to do this is to use the append method on your list. The reason you're getting an out of range error is because you're saying:
list1 = []
list1.__getitem__(0)
and then manipulate this item, BUT that item does not exist since your made an empty list.
Proof of concept:
list1 = []
list1[1]
IndexError: list index out of range
We can, however, append new stuff to this list like so:
list1 = []
for i in range(5):
list1.append(i * 2)
Say I have an array thusly:
a = [1, 2, 3, 4]
I want to have it be printed like so:
1
2
3
4
but I don't want to go:
print(a[0])
print(a[1])
print(a[2])
print(a[3])
I want it to automatically print each entry, but dynamically enough so that it stops when there is nothing more, but keeps going if there is, if that makes any sense. I'm not very good at words when it comes to programming, but I hope this makes sense.
Join the list together with linefeeds:
print '\n'.join(a)
Use a loop:
for x in a:
print x
Obligatory Python3 answer:
[print(k) for k in a]
print is a function in Python3.