0

How to delete element in an array without using python builtin functions

I have tried this program with builtin functions, but I do not know how to do it without them

c = [6,7,8,9]
c.remove(c[0])
print(c)

I am getting expected result but I want it without using the built-in function in python.

6
  • 2
    Basically every operation on a list (!) will call a method of it. Commented Aug 30, 2019 at 13:07
  • you want to say, without using .remove method? Commented Aug 30, 2019 at 13:10
  • you mean not to use del keyword? there are no delete methods on lists Commented Aug 30, 2019 at 13:20
  • 1
    @rusu_ro1 yes brother without using remov & del functions,as we use to do in java. Commented Aug 30, 2019 at 13:20
  • you want to remove all the elements that have a certain value, or by index, so you want to delete a certain element? Commented Aug 30, 2019 at 13:29

4 Answers 4

1

This should do it, but this method creates a new array

c=[6,7,8,9]
d=[]
a=0
for x in c:
   if x!=c[a]: #or you write c[0] and remove the a=0
      d.append(x)

print(d) 
Sign up to request clarification or add additional context in comments.

Comments

1

you could use a list comprehension:

c = [ e for e in c if e != c[0] ]

However, if you have multiple instances of the c[0] value, they will all be removed.

removing by index can also be done using a list comprehension:

c = [ e for i,e in enumerate(c) if i != 0 ]

Comments

0

if you know the index of the element that you want to remove:

1) you can concatenate 2 slices of your list that has all the elements except the one you want to remove:

index_to_remove = 0
c = c[0:index_to_remove] + c[index_to_remove + 1:]

2) or by filtering using list comprehension:

c = [e for i, e in enumerate(c) if i != index_to_remove]

if you just want to delete the first element that has a certain value you can use the same methods, you just set:

index_to_remove = c.index(my_value)

2 Comments

thanks for the help, code is working perfectly but i have one more question what does c = [e for i, e in enumerate(c) if i != index_to_remove] this statement do? i have used it but i do not know whats going in it.
enumerate will give you the index and the value, just make sure you are not keeping the index that you wan to remove (if i!= index_to_remove)
0
from array import *   
arr = array("i",[2,4,6,8,9])        
del arr[2]         
print(arr) 

output-array("i",[2,4,8,9])

1 Comment

The OP didn't want to use the del method - however, I also don't know why.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.