Remove or pop is not eliminating all the elements [duplicate] - python

This question already has answers here:
Why does Python skip elements when I modify a list while iterating over it?
(8 answers)
Closed 2 years ago.
lis = [3,4,5,6]
for j in lis:
lis.remove(j)
print(lis)
Output:
[3,4]
I tried pop() also but couldn't remove all elements

The reason why you are not able to remove all the elements is that when you are removing an element from the array the j value skips to the next value's next value instead of the next. So only the alternative values will be removed by this method.
lis = [3,4,5,6]
for j in lis:
lis.remove(j)
print(j)
print(lis)
Output
3
5
[4,6]
As you can see in this output print(j) does not print all the elements, it only prints 3 and 5. So only 3 and 5 are removed.
How to solve it?
So you can either use clear(), like this
lis.clear()
Or if you want to use iteration you can do it with pop() like this
for i in range(len(lis)):
lis.pop(i)
Or you can create a shallow copy of the list and remove() the elements one by one like this
for i in list(lis):
lis.remove(i)
Or you can use : to return the whole slice of the array (copy of the array)
for i in x[:]:
x.remove(i)

use clear to clear all the element of the list
lis =[3,4,5,6]
lis.clear()
print(lis)
Output:
[]

A correct solution will be to create a shallow copy with the help of list() function.
lis =[3,4,5,6]
for j in list(lis):
lis.remove(j)
print(lis)
Output
[]

Related

How to delete record from a nested list in a loop? [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 1 year ago.
I have nested list like that [a,1],[b,2],[c,3]
My code:
for i in list:
if i[0] == 'b':
del i
And thats just not working. Code do not crash, but it does not delete neither.
I was trying something like that:
for i in list:
if something:
del i[1]
del i[0]
But it returns [a,1],[],[c,3] and i am not satisfied with that.
It is not a good idea to delete from a list while iterating over it at the same time, try using a list comprehension instead:
List = [L for L in List if L[0] != 'b']
You can use the enumerate method for that purpose. Take a look at the code snippet below.
li = ['a' , 'b' , 'c' , 'd']
for i , elm in enumerat(li):
if elm == 'a':
del li[i]
Using the enumerate function, you'll have access to two values. The first value, i in the code is the index of the element and the second value is the element itself.
You can check the elements in self in each iteration and then use the index to modify the list as needed.
The other answer is great, but to answer your question (even if it is not a good practice to delete while iterating):
list = [['a',1],['b',2],['c',3]]
for i in list:
if i[0] == 'b':
list.remove(i)
print(list)
You could also avoid deleting from the list you're iterating through like this:
list = [['a',1],['b',2],['c',3]]
for i in list.copy():
if i[0] == 'b':
list.remove(i)
print(list)
The list comprehension in the other example is cleaner and more readable, though.

IndexError in Python 3 [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 2 years ago.
When I am trying to initialize an empty list in Python 3.7.3 using the following code snippet, it is throwing an index error. Can anyone please explain the cause and recommend some corrective action?
newlist = list()
x = 2
for i in range(0, 5):
newlist[i] = x*2
print(newlist)
O/P: IndexError: list assignment index out of range
This is not related to python version. The newlist is empty and you cannot access empty list which gives the error.
If you look step by step:
newlist = list()
Viewing newlist at this point gives as:
print(newlist)
will give: []
In the for loop i starts from 0 so, first iteration of the loop will cause:
newlist[0] = x*2
which gives IndexError since list is empty you cannot access by index. So what you probably need is .append to add to the newlist as following:
newlist = list()
x = 2
for i in range(0, 5):
newlist.append(x*2) # <-- Append to newlist
print(newlist)
You can only access elements at indexes, that exist.
So you have to append elements first:
newlist = list()
x = 2
for i in range(0, 5):
newlist.append(x*2)
print(newlist)
Your code is trying to "inject" the value of x*2 into a list at 4 index locations, however, your list is already empty.
So, how can you access those indices to "inject" values into which do not exist in the first place?
You can rectify your code by using append() method which will keep on adding the value of x*2 to the end of the list on each iteration, thereby, creating the required indices in the process:
newlist = list()
x = 2
for i in range(0, 5):
newlist.append(x*2)
print(newlist)
Hope this clarifies.
A pythonic way to do what you want
x=2
newlist = [x*2 for x in range(0,5)]
print(newlist)

How can I remove multiple elements from a list? [duplicate]

This question already has answers here:
Different ways of clearing lists
(8 answers)
Closed 4 years ago.
list1 = [2,5,61,7,10]
list1.remove(list1[0:len(list1)-1])
print(list1)
I want to remove all elements from that list but it shows me syntax error.
Any idea how can I remove all elements and print the final result like []
To remove all list items just use the in-built .clear() function:
>>> list1 = [2,5,61,7,10]
>>> list1.clear()
>>> print(list1)
[]
>>>
If you want to remove all elements from a list, you can use the slice assignment:
list1[:] = []
But with list.remove(), you can only do it one-by-one:
for item in list(list1):
list1.remove(item)
Note I created a copy of list1 with the for loop because it's dangerous to modify what you're iterating over, while it's safe to modify the list while iterating over a copy of it.
To remove some of the items:
for item in list1[0:3]:
list1.remove(item)
Or just better yet, use slice assignment:
list1[0:3] = []

append function in python [duplicate]

This question already has answers here:
Ellipsis lists [...] and concatenating a list to itself [duplicate]
(3 answers)
Closed 6 years ago.
I have a list X = ['xyz']
I use the below commands for appending to another variable.
L = X
L.append(X)
L
Out[109]: ['xyz', [...]]
I am unable to understand why the second element in the new L list is not having the value as 'xyz'
My question is not how to append or extend a list, but in fact about the functionality of Append function, which has been correctly explained by #sinsuren below.
append add X as an element to L. If you want the element inside X to be inserted to L, use extend instead:
>>> X = ['xyz']
>>> L = X
>>> L.extend(X)
>>> L
['xyz', 'xyz']
Try this, it will extend the list.
L.extend(X)
But if you want to use append. Use a element like this L.append('abc'). It will give same result or L.append(X[0])
Edit: You have Appended list to itself. It will recursively append to itself and due to which even L[1] will give you same response. Like L[1] = ['xyz', [...]] . and for more understanding Please refer What's exactly happening in infinite nested lists?

Delete list elements after using them [duplicate]

This question already has answers here:
Strange result when removing item from a list while iterating over it
(8 answers)
Closed 7 years ago.
I have a list
test_list = [1,2,3,4,5]
I want to iterate over the elements of this list and delete them after using. But when I try to do this
for element in test_list:
print element
test_list.remove(element)
Alternate elements are printed and removed from test_list
1
3
5
print test_list
[2, 4]
Please explain why this happens!
Read the answers to strange result when removing item from a list to understand why this is happening.
If you really need to modify your list while iterating do this:
>>> items = ['x', 'y', 'z']
>>> while items:
... item = items.pop()
... print item
...
z
y
x
>>> items
[]
Note that this will iterate in reverse order.
in python this concept is called an iterator
my_iter = iter(my_list)
each time you consume or look at an element it becomes gone ...

Categories

Resources