+ 2
How delete all num 2?
# i want output -[1,5,7,6,7,3,8] words = [1,2,5,7,2,6,7,3,2,2,2,2,2,8]
17 Antworten
+ 3
# i want output -[1,5,7,6,7,3,8]
words = [1,2,5,7,2,6,7,3,2,2,2,2,2,8]
output = []
for i in words:
if i !=2:
output.append(i)
print(output)
+ 8
1#your list with duplicate values
2duplicates=[1,2,5,7,2,6,7,3,2,2,2,2,2,8]
3
4#print unique duplicates list
5print(list(set(duplicates)))
6
7#A list with small numbers
8smallNumbers=[2]
9
10#print the unique duplicates list without small numbers
11list(set(duplicates)-set(smallNumbers))
+ 7
you may try above ☝️program
+ 6
You can apply a filter on the list:
print(list(filter(lambda x: x!=2, words)))
or use a list comprehension:
print([x for x in words if x!=2])
+ 3
𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 Try it this way - there are 11 2s in the words list initially, right? The iterator goes through the list and *removes* the first met instance of the argument. And then the index skipping happens.
So out of 11, it will only match i==2 six times. So only 6 2s will be removed. And since .remove delete the *first met* instances, it will remove the first six 2s from the list.
+ 2
𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 As you wrote it .remove(2) is applied on the whole words list each time the iterated element is equal to 2.
So the first time it happens is when the iterated index is equal to 1 (words[1] is the first time the condition is True).
The element with index 1 gets removed and the iteration goes on. BUT... it already skips to words[2] which is now 7. And 5 gets skipped.
That doesn't hurt our iterator now, but is fatal for the ending list elements, where there are consecutive 2s.
The same rule applies after the first 2 is reached - it gets removed and the iterator *skips the next element* which... happens to be 2, too. So you have at least one case when 2 will not be removed. As there are similar consecutive cases, there will be more 2s left out in the end.
Try removing the conditional part and see what happens.
+ 2
words=[x for x in words if x!=2]
thats all!!!!
also you can assigne new words if do not want to change words, or make function
+ 1
𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥
As your code iterates through the list, it is removing i, when i==2.
This causes the list to get shorter, which allows the iteration to skip over sequential 2's.
Hope this makes sense.
+ 1
Bruklin Here is my way to remove element.
https://code.sololearn.com/cAsLt04fSp6f/?ref=app
Other options are doing copy or creating new list. My code is operating on the same list.
Let me know if you have any questions.
+ 1
You can also try this:
words = [1,2,5,7,2,6,7,3,2,2,2,2,2,8]
for i in range(words.count(2)):words.remove(2)
print(words)
+ 1
Every each code is good ☝☝👍👍💖
0
Rohit Salve Your code is not working. I have commented to your code. Please check and solve it.