This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 5 years ago.
I did one simple code to separate elements of an array into two new arrays : one with odd numbers and other with even numbers. So I did this:
V=[1,2,3,4,5,6]
vp=[]
vi=[]
for x in V:
if x%2==0:
vp.append(x)
V.remove(x)
else:
vi.append(x)
V.remove(x)
print (V)
print (vp)
print (vi) # sorry for the bad identation first time sharing code here
and this code give me this result:
[2,4,6]
[]
[1,3,5]
How is it happen? How am I fix this?
You shouldn't remove item while traversing an array:
V=[1,2,3,4,5,6]
vp=[]
vi=[]
for x in V:
if x%2==0:
vp.append(x)
else:
vi.append(x)
Modifying a list mid-iteration causes misbehavior (you effectively skip input elements). Don't remove from V as you go (which for long V would be expensive, each remove is O(n) making total work O(n**2)), just leave V unmodified. If necessary, clear V when you finish (a single O(n) operation), e.g. after the loop:
del V[:]
When you remove items from a list, the list gets shorter. So when you're looping over a list in a forward direction, removing items will cause the the iterator to skip forward.
To mitigate this, you can loop backwards over a list and safely remove items, since you're removing them from the end.
V = [1,2,3,4,5,6]
vp = []
vi = []
# reverse the list before iterating
for x in reversed(V):
if x % 2 == 0:
vp.append(x)
V.remove(x)
else:
vi.append(x)
V.remove(x)
Other answers that identified the problem and the fix, but here is a different way to do it using list comprehensions.
numbers = [1,2,3,4,5,6]
even = [e for e in numbers if e % 2 == 0]
odd = [e for e in numbers if e % 2 == 1]
A more concise way to make a new odd and even list from the original is to use comprehensions:
v = [1,2,3,4,5,6]
even = [number for number in v if number % 2 == 0]
odd = [number for number in v if number % 2 != 0]
Don't remove items from a list over which you are iterating. Use a copy:
V=[1,2,3,4,5,6]
vp=[]
vi=[]
for x in V[:]:
if x%2==0:
vp.append(x)
V.remove(x)
else:
vi.append(x)
V.remove(x)
print (V)
print (vp)
print (vi)
# []
# [2, 4, 6]
# [1, 3, 5]
Related
This question already has answers here:
Strange result when removing item from a list while iterating over it
(8 answers)
Closed last year.
This is the code I have used and it is not removing last zero it is skipping
x = [1,2,3,0,0,0]
for I in x:
if I==0:
x.remove(I)
print(x)
output:
[1, 2, 3, 0]
so from the output the last zero is not removing why
Why don't you use this simple list comprehension.
x = [1,2,3,0,0,0]
y=[i for i in x if i != 0]
print(y)
You'll get a new list (y) with the 0 removed, while the x is preserved in it's original state.
[1, 2, 3]
Process finished with exit code 0
For more study on list.remove(), check this
List.remove() does not remove all occurrances
As per documentation, list.remove removes first element whose value matches given number.
So, when first '0' at index 3 is removed, the new list is [1,2,3,0,0] with the list iteration index at 4. The following 0 (which was at index 4 in original list) moves back one place and is getting skipped. This can be seen with following code:
x = [0,0,0,0,0,0]
for id, i in enumerate(x):
print(id, i)
if i == 0:
print(x, i)
x.remove(i)
print(x)
In this, every second element is missed, and final x is [0, 0, 0]
As for what is correct way to do this, list comprehension is a good way, as answered by Anand: x = [i for i in x if i!=0]
This question already has answers here:
How to add 1 to every element of a matrix / nested list in Python?
(4 answers)
Closed 1 year ago.
I need to add 0.05 to elements of coords array. But nothing happens.
Can you advise me where is the mistake? (I thought this would be easy but no)
coords = [[0.1,0.1,0.1],
[0.2,0.2,0.2],
[0.3,0.3,0.3]]
for i in coords:
for j in i:
j = j+0.05
print(coords)
Your solution doesn't actually modify the elements in the list by iterating over j. You could try a double list comprehension like this:
coords[:] = [j+0.05 for i in coords for j in i]
This has the advantage of editing the original object without creating a new instance of a list.
You current way will not store the results, as you did not provide a list to hold the results. I can show you two more straightforward examples:
a = [1,2,3,4]
for number in a:
number = number + 1
# check results
# nothing happens
print(a)
But if you do:
# you will get results
b = [number + 1 for number in a]
print(b)
The only difference is that you need to provide a list to hold the data.
Try this:
coords = [[0.1,0.1,0.1],
[0.2,0.2,0.2],
[0.3,0.3,0.3]]
for i in range(len(coords)):
for j in range(len(coords[i])):
coords[i][j] += .05
print(coords)
You can use lst comprehension
coords = [[0.1,0.1,0.1],
[0.2,0.2,0.2],
[0.3,0.3,0.3]]
newCoords = [[num+0.05 for num in lst] for lst in coords ]
print(newCoords)
I have a problem. I need to create a list . And in every iteration i need to remove the third element and print the list without the deleted element.
The thing is. I'm trying to do an algorithm of deleting the third element without remove function or other inbuilt list functions. In my code I covered the following possibilities. If my list has less than 3 elements I print a message saying the list is short. If my list has 3 elements in it I will assign the third element the value of the second element and so on. My problem is when my list has more than 3 elements.
v=[] # list of numbers the user inputs
two=[] #list with only 2 elements
vector=[] # list with third element deleted when len(v)>3
def create_array():
n=int(input('Digit total elements in dynamic array - '))
for i in range(0,n):
element=int(input('Digit element to array - '))
v.append(element)
return v
print(create_array())
def remove_third_element():
for j in range(0,len(v)):
if len(v)<3: # if number of elements in list < 3 there is no element to delete
print('There is no element do delete! ')
return 0
elif len(v)==3:
v[2]==v[1] and v[1]==v[0]
two=[v[0],v[1]]
return two
else:
v[0]==v[1] and v[1]==v[2]
print(remove_third_element())
elif len(v) > 3:
ret = [];
for i in range(len(v)):
if(i != 2) ret.append(v[i]);
return ret
should do the trick
By the way, with this method you can remove you elif len(v) == 3
Also your code :
elif len(v)==3:
v[2]==v[1] and v[1]==v[0]
two=[v[0],v[1]]
return two
won't work because '==' is used as condition in python so it will return a boolean and not assign value.
go for
v[2] = v[1]
v[1] = v[0]
instead
Here's a Pythonic way of making a new list without the original list's third element.
new_list = old_list[:2] + old_list[3:]
old_list[:2] is shorthand for "until the 2-th index" (so we'll get index 0 and 1) of the old_list.
old_list[3:] is shorthand for, "from 3rd index 'til the end" (so index 3, 4, etc.).
Both return lists; in python, if you add lists, concatenation actually happens.
As an example, if old_list = [1,2,3,4,5], then new_list[:2] will be [1,2] and new_list[3:] will be [4,5]. So combining that will be [1,2,4,5].
Notice that this statement: v[2]==v[1] and v[1]==v[0] won't assign values!
Operation == return boolean.
Lets say your v looks like this: v = [1, 1, 3].
Then v[2]==v[1] and v[1]==v[0] gives you result: False and True, and this gives you reulst False. You can check it if you print this print(v[2]==v[1] and v[1]==v[0]).
If you want to assign values, you can use a statement like this: v[2], v[1] = v[1], v[0].
def main():
big_list = [ x for x in range(20) ]
while len(big_list) > 3:
big_list = big_list[:2] + big_list[3:]
print(big_list)
This question already has answers here:
Python: Finding differences between elements of a list
(12 answers)
Difference between consecutive elements in list [duplicate]
(3 answers)
Closed 4 years ago.
here is my code.
A = [86.14803712, 85.25496701, 86.50334271, 86.0266668, 86.61455594, 86.90445213, 86.65519315, 87.10116762, 87.08173861]
B = []
i = 0
for i in range(len(A)):
c = A[i]-A[i-1]
B.append(c)
print(c)
I want to get the differences between two continuous numbers in this list, eg,(85.25496701-86.14803712). So in the results, I should have eight numbers as results.
But the results I get are:
-0.9337014900000042
-0.8930701099999965
1.2483756999999969
-0.4766759099999973
0.5878891400000015
0.2898961899999932
-0.24925897999999336
0.4459744699999959
-0.019429009999996083
I don't need -0.9337014900000042 since it comes from the first number subtract the last number in the list. What should I do the fix it? Thanks
That's the strength and the weakness of python: index -1 is always valid when the list isn't empty, which can lead to programs not crashing but not doing what you want.
For those operations, it's better to use zip to interleave the list with a sliced version of itself without the first number:
A = [86.14803712, 85.25496701, 86.50334271, 86.0266668, 86.61455594, 86.90445213, 86.65519315, 87.10116762, 87.08173861]
diffs = [ac-ap for ac,ap in zip(A[1:],A)]
or with itertools.islice to avoid creating a new list to iterate on it:
import itertools
diffs = [ac-ap for ac,ap in zip(itertools.islice(A,1,None),A)]
result (8 values):
[-0.8930701099999965, 1.2483756999999969, -0.4766759099999973, 0.5878891400000015, 0.2898961899999932, -0.24925897999999336, 0.4459744699999959, -0.019429009999996083]
It's possible to do this in base Python, but you might like the semantic clarity of Pandas:
import pandas as pd
pd.Series(A).diff().values[1:]
array([-0.89307011, 1.2483757 , -0.47667591, 0.58788914, 0.28989619,
-0.24925898, 0.44597447, -0.01942901])
You can just do:
B = [x-y for x, y in zip(A[1:], A)]
print(B) # -> [-0.8930701099999965, 1.2483756999999969, -0.4766759099999973, 0.5878891400000015, 0.2898961899999932, -0.24925897999999336, 0.4459744699999959, -0.019429009999996083]
You need to make sure you star from a correct index. In your current code, in the first iteration of the loop you will be computing A[0] - A[-1]. Hence, you need to start i from 1 to ensure in the first iteration you compute the value of A[1] - A[0]. The corrected version of your code is here:
A = [86.14803712, 85.25496701, 86.50334271, 86.0266668, 86.61455594, 86.90445213, 86.65519315, 87.10116762, 87.08173861]
B = []
i = 0
for i in range(1, len(A)):
c = A[i]-A[i-1]
B.append(c)
print(c)
I think the problem is that the loop subtracts the first element to the last because the loop starts at index 0 and subtracts it from index -1 (python takes -1 as the last index of a list). A better solution imo would be:
A = [86.14803712, 85.25496701, 86.50334271, 86.0266668, 86.61455594,
86.90445213, 86.65519315, 87.10116762, 87.08173861]
B = []
i = 0
for i in range(len(A)-1):
c = -(A[i]-A[i+1])
B.append(c)
print(c)
The easiest would be:
result = [x-y for x,y in zip(A[1:], A[:-1])]
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
For example, the lists are [1,2,3],[4,5,6], and [7,8,9]. I want to add only the even numbers up in all the lists, so that would be 2+4+6+8=20. How would I go about doing this?
You can just do it like this for example:
l = [[1,2,3], [4,5,6], [7,8,9]]
sum(val for v in l for val in v if val % 2 ==0)
Simply loop through each list, and sum up the even values.
theSum = 0
lists = [[1,2,3],[4,5,6],[7,8,9]]
for list in lists:
for item in list:
if item % 2 == 0:
theSum += item
The (%) sign used in this context is known as modulus, it will return the number of remainders when a number is divided by another. So far example here, any number that can be divided by 2 without any remainders is an even number e.g. 8 % 2 returns 0.
if item % 2 == 0:
theSum += item
As you can see by the if statement, we go through all the items and test if they can be divided by 2 without leaving remainders. If they can be, we add them together.
Here is more information about modulus.
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
sum = 0
for x in a+b+c:
if x%2 == 0:
sum += x
There are many solutions, but here is a good start for you.
You can merge all the lists together into one list:
lst =[1,2,3] + [4,5,6] + [7,8,9]
Then you can make a list of just the evens:
new_list = [n for n in lst if is_even(n)]
Note: you must write is_even
def is_even(n):
# return True if even
# otherwise return False
Then you can iterate through the list and add up all the numbers in the list.
a=[1,2,3]
b=[4,5,6]
c=[7,8,9]
sum(filter(lambda x:x%2==0,a+b+c))