My answer is not exactly to your question but after you read this, I hope you can decide which type you need to choose for your needs.
Python’s lists are variable-length arrays, not Lisp-style linked lists. The implementation uses a contiguous array of references to other objects, and keeps a pointer to this array.
This makes indexing a list a[i] an operation whose cost is independent of the size of the list or the value of the index.
When items are appended or inserted, the array of references is resized. Some algorithm is applied to improve the performance of appending items repeatedly; when the array must be grown, some extra space is allocated so the next few times don’t require an actual resize i.e over-allocation. More Information
Removing vs Pop vs Delete:
At first glance it looks like all of them are doing the same thing.
Under the hood its behaving different.
removing : remove an element from the list by iterating from 0 index till the first match of the element is found. taking more time to iterate if the element is at the end.
pop : removing element from the list by using the index. taking less time.
del : is a python statement that removes a name from a namespace, or an item from a dictionary, or an item from a list by using the index.
REMOVE:
- it removes the first occurence of value.
- raises ValueError if the value is not present.
- it takes only one argument, so you can't remove multiple value in one shot.
POP:
- remove and return item at index (default last).
- Raises IndexError if list is empty or index is out of range.
- it takes only one argument, so you can't remove multiple value in one shot.
DEL:
- remove the item at index and return nothing.
- it can remove slices from a list or can clear the whole list.
Benchmark:
Worst case : deleting from the end of the list.
yopy:-> python -m timeit "x=range(1000)" "x.pop(999)"
100000 loops, best of 3: 10 usec per loop
yopy:-> python -m timeit "x=range(1000)" "x.remove(999)"
10000 loops, best of 3: 31.3 usec per loop
yopy:-> python -m timeit "x=range(1000)" "del x[999]"
100000 loops, best of 3: 9.86 usec per loop
yopy:->
Best case: begining of the list.
yopy:-> python -m timeit "x=range(1000)" "x.remove(1)"
100000 loops, best of 3: 10.3 usec per loop
yopy:-> python -m timeit "x=range(1000)" "x.pop(1)"
100000 loops, best of 3: 10.4 usec per loop
yopy:-> python -m timeit "x=range(1000)" "del x[1]"
100000 loops, best of 3: 10.4 usec per loop
yopy:->
Point to be noted:
if array grows or shrinks in the middle
- Realloc still depends on total length.
- But, All the trailing elements have to be copied
So, now I hope you can decide what you need to choose for your needs.
Answer from James Sapam on Stack OverflowMy answer is not exactly to your question but after you read this, I hope you can decide which type you need to choose for your needs.
Python’s lists are variable-length arrays, not Lisp-style linked lists. The implementation uses a contiguous array of references to other objects, and keeps a pointer to this array.
This makes indexing a list a[i] an operation whose cost is independent of the size of the list or the value of the index.
When items are appended or inserted, the array of references is resized. Some algorithm is applied to improve the performance of appending items repeatedly; when the array must be grown, some extra space is allocated so the next few times don’t require an actual resize i.e over-allocation. More Information
Removing vs Pop vs Delete:
At first glance it looks like all of them are doing the same thing.
Under the hood its behaving different.
removing : remove an element from the list by iterating from 0 index till the first match of the element is found. taking more time to iterate if the element is at the end.
pop : removing element from the list by using the index. taking less time.
del : is a python statement that removes a name from a namespace, or an item from a dictionary, or an item from a list by using the index.
REMOVE:
- it removes the first occurence of value.
- raises ValueError if the value is not present.
- it takes only one argument, so you can't remove multiple value in one shot.
POP:
- remove and return item at index (default last).
- Raises IndexError if list is empty or index is out of range.
- it takes only one argument, so you can't remove multiple value in one shot.
DEL:
- remove the item at index and return nothing.
- it can remove slices from a list or can clear the whole list.
Benchmark:
Worst case : deleting from the end of the list.
yopy:-> python -m timeit "x=range(1000)" "x.pop(999)"
100000 loops, best of 3: 10 usec per loop
yopy:-> python -m timeit "x=range(1000)" "x.remove(999)"
10000 loops, best of 3: 31.3 usec per loop
yopy:-> python -m timeit "x=range(1000)" "del x[999]"
100000 loops, best of 3: 9.86 usec per loop
yopy:->
Best case: begining of the list.
yopy:-> python -m timeit "x=range(1000)" "x.remove(1)"
100000 loops, best of 3: 10.3 usec per loop
yopy:-> python -m timeit "x=range(1000)" "x.pop(1)"
100000 loops, best of 3: 10.4 usec per loop
yopy:-> python -m timeit "x=range(1000)" "del x[1]"
100000 loops, best of 3: 10.4 usec per loop
yopy:->
Point to be noted:
if array grows or shrinks in the middle
- Realloc still depends on total length.
- But, All the trailing elements have to be copied
So, now I hope you can decide what you need to choose for your needs.
Use a list comprehension:
Scenario 1:
[item for item in my_list if 1 <= item <=5 ]
Scenario 2:
to_be_removed = {'a', '1', 2}
[item for item in my_list if item not in to_be_removed ]
Scenario 3:
[item for item in my_list if some_condition()]
Scenario 4(Nested list comprehension):
[[item for item in seq if some_condition] for seq in my_list]
Note that if you want to remove just one item then list.remove, list.pop and del are definitely going to be very fast, but using these methods while iterating over the the list can result in unexpected output.
Related: Loop “Forgets” to Remove Some Items
Removing a specific element from a list
python - Is there a simple way to delete a list element by value? - Stack Overflow
How do I remove an element from the end of a list without returning the value? (Python)
How to delete all the items (in a list) beautifully?
I have a function that receives two lists. The goal is for the function to return lst1 without the elements on lst2, however I'm having trouble with that. What can I do?
I do have to say that I cannot use any while or for loop, only recursion (that's the hard part)
def minus(lst1,lst2):
element = lst2.pop()
if element is in lst1:
#how can I find the position of the elements in lst1 that is equal to "element"?
else:
if len(lst2) == 0:
return lst1
else:
return minus(lst1,lst2)To remove the first occurrence of an element, use list.remove:
>>> xs = ['a', 'b', 'c', 'd']
>>> xs.remove('b')
>>> print(xs)
['a', 'c', 'd']
To remove all occurrences of an element, use a list comprehension:
>>> xs = ['a', 'b', 'c', 'd', 'b', 'b', 'b', 'b']
>>> xs = [x for x in xs if x != 'b']
>>> print(xs)
['a', 'c', 'd']
Usually Python will throw an Exception if you tell it to do something it can't so you'll have to do either:
if c in a:
a.remove(c)
or:
try:
a.remove(c)
except ValueError:
pass
An Exception isn't necessarily a bad thing as long as it's one you're expecting and handle properly.
Hi, so I am writing a class for doing some methods on a list.
I already know how to add an element to the end of a list by using the append() method.
However if I want to remove an element from the end of a list, without returning the value, how would I go about that? I know the pop() method can remove an element from the end of a list but it then returns the value of that element. What kind of method can I include in my class that will remove an element from the end of the list?
SOLVED
list1 = [12, 20, 10, 14, 54, 16, 75, 38, 79, 103,105]
chicken = len(list1)
if chicken %2 != 0:
chicken = (chicken / 2) - 0.5
list1.remove(chicken)
print (list1)
Sorry I know my variable names are weird for the time being. one of the assignments is requiring us look at list, remove the middle variable if the length of the list is odd, or remove the middle two elements if the length of the list is even, I started on the odd part first because I thought it would be easier but im running into a problem. I want to remove the middle element of the list, however it isn't as simple as remove the number in the exact spot since this has to work for any odd length of a list, I've been able to write a formula to find the middle number of every odd list but the problem is I don't know how to remove the middle element, logically to me it would make sense that removing the number from the exact point in the list would make sense, but it seems that with the remove function its requiring you to have the specific string in order to remove it. When I run the code it tells me
Traceback (most recent call last):
File "C:/Users/derpd/Downloads/listy.py", line 28, in <module>
list1.remove[chicken]
TypeError: 'builtin_function_or_method' object is not subscriptable
I tried using brackets but that didn't seem to work either, any tips or ideas on how I can remove the middle element, I understand how to get the middle element just not how to remove it