Delete items from array in Python [duplicate] - python

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 7 years ago.
I want to delete word sabin from the array but it is showing some error...
array=["sabin","ram","hari","sabin"]
length=len(array)
for steps in range(length):
if(array[steps]=="sabin"):
print("removed=%s"%(array[steps]))
del array[steps]
length=len(array)
print(length)

you could do this with a list comprehesion:
array=["sabin","ram","hari","sabin"]
length=len(array)
array = [x for x in array if not x == 'sabin']
length=len(array)

The error that you are receiving is an IndexError. This is because you are removing values from the list, while still iterating over it. One possible solution is to use the remove method of the list object to remove instances of "sabin":
array=["sabin","ram","hari","sabin"]
to_remove = 'sabin'
while to_remove in array:
array.remove(to_remove)
print("removed=%s"%(to_remove))
print(len(array))
This avoids the IndexError since it is not dependent on the index staying the same throughout the loop.

You can use filter too!
my_list = ["sabin","ram","hari","sabin"]
print(my_list)
>>> ['sabin', 'ram', 'hari', 'sabin']
my_list = filter(lambda x: x != 'sabin', my_list)
print(my_list)
>>> ['ram', 'hari']

Related

List index out of range in loop [duplicate]

This question already has answers here:
python : list index out of range error while iteratively popping elements
(12 answers)
Closed 2 years ago.
Im getting an error for list index being out of range. Sorry if this is a stupid question.
def filter_list(l):
for x in range(0, len(l)):
if type(l[x]) is str:
del l[x]
return l
When you use del to delete the item in the list, the list actually shortens and it seems like that is what is causing the problem.
If you would like to filter lists, you could use list comprehensions like so:
def filter(l):
return [item for item in l if type(item) is not str]
Usually, when looping over lists, it is good practice not to delete or insert new items.
Hope this helped
You should not definitely change a list while iterating over it. It is very bad practise... it can lead to a whole lot of errors for you. Either you should create a copy of use something else, as list comprehension:
def filter_list(l):
return [x for x in l if type(x) is not str]
print(filter_list([1, 4, 5, 's', 'demo'])) # Prints [1, 4, 5]

Python removing duplicates in list [duplicate]

This question already has answers here:
Removing duplicates in lists
(56 answers)
Closed 2 years ago.
How can I remove duplicates from this list?
x = [name, code]
Some elements of list has the same code:
list = [['cafe', '/fr/48349066'], ['cafe', '/fr/48349056'], ['cafe', '/fr/48349066']]
There's probably a more processing-efficient way to do this, but this is the way I've always done stuff like this:
for i in range(len(list)):
for j in range(len(list)):
if list[i][1] == list[j][1]:
list.pop(i)
There is a lot of ways to removing duplicates;
1-) The Naive Method;
new_list = []
for i in some_list:
if i not in new_list:
res.append(i)
2-) Using list comprehension;
new_list = []
[new_list.append(x) for x in some_list if x not in new_list]
3-) Using set();
some_list = list(set(some_list))
4-) Using collections.OrderedDict.fromkeys()
from collections import OrderedDict
new_list = list(OrderedDict.fromkeys(some_list))

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] = []

Python: strange issue where conditionally removing elements from a list [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 6 years ago.
(I see that this question is a duplicate. Sorry everybody, I wasn't sure of the wording so I couldn't find the other question)
I define the following list of strings:
x=["foo_a","foo_a_b","foo"]
then I do the following:
for i in x:
if (("a" not in i) or ("b" in i)):
x.remove(i)
and I get
In [92]: x
Out[92]: ['foo_a', 'foo']
I would expect the element "foo" to be removed too, because it doesn't contain "a" and so it doesn't verify the first condition.
What am I missing?
You are modifying the list you are iterating on. Iterate over a copy of x:
x=["foo_a","foo_a_b","foo"]
for i in list(x):
if (("a" not in i) or ("b" in i)):
x.remove(i)
Or even better, avoid using a for loop and create a new list with a list comprehension and assign it to x
x = ["foo_a","foo_a_b","foo"]
x = [item for item in x if not (("a" not in i) or ("b" in i))]

Categories

Resources