Log In  

How to delete an element in table instead of using

x = {10,40,70}
x[2] = nil

Because it will make an element empty

x = {10,nil,70}

Expected result is

x = {10,70}
P#120032 2022-11-03 09:05

Use del(x, x[2]) and it'll delete item 2.

P#120034 2022-11-03 09:34

Thanks, but it seems del(x, 2) is right

P#120035 2022-11-03 09:49
1

I don't think it is. del(x, x[2]) means find the element that is at the second second index and delete that element. Note that this will give the wrong value if there are repeated values and you want to delete the not last one

x={10,20,30,40,30}
del(x,x[5])
foreach(x,print)

this outputs

10
20
40
30

which is not what was expected

x={10,20,30,40,30}
del(x,2)
foreach(x,print)

this returns the entire list unchanged.

10
20
30
40
30

What I think you actually want is deli (delete index)

x={10,20,30,40,30}
deli(x,5)
foreach(x,print)

gives

10
20
30
40

I believe this is the expected result.

P#120039 2022-11-03 11:13 ( Edited 2022-11-03 11:13)

@SquidLight Ha! I totally forgot deli() was a thing! So handy.

P#120072 2022-11-03 15:26

[Please log in to post a comment]