What is the difference between the structure of these functions?

Viewed 65

I'm studying Python now, and sometimes a book says that if we have an list whose structure is, for example, a = [1,2,3,4,5], then we can use either

del a[0] or a.append[0].

I can understand the meaning of these functions but not the structure. Why can't I use instead

a.del[0] or append a[0]?

What is the difference or is there any rules or something?

2 Answers

.append is used to add an element to the list, so i'll explain it with .pop which is closer to del. Both 'del' and '.pop' can remove an element at a certain index.

.pop() Removes the item with the index from an array and then returns that value. example:

b = a.pop(1)
print(b) #will print '2'
print(a) #will print [1,3,4]

del is a keyword used in python, it's not only for lists, it works on any object(variables, function, lists...)

#with del it wont return a value
b = del a[1] #wont return a value and will give an error

Both ways can delete an element of a list, but they're both used for different reasons.

Now for the difference of structures, del is made to delete an object so if you said 'del a' it would delete the whole list. So when you want to delete one element your saying delete the object a[1] which deletes index 1 of a (del a[1]).

But for .pop() it wont delete any object its used for lists, just like .append(). They both are built-in function which are used on lists.

To answer your question - it's best to go by the official documentation - https://docs.python.org/3/tutorial/datastructures.html

First, a is a list, it contains [1, 2, 3, 4, 5]. list.append() is one of list's method. Other similar methods: list.remove(x), list.pop(), etc. But delete() is different - it's a "statement" (And there is NO append statement!)

list.append(x)
Add an item to the end of the list. Equivalent to a[len(a):] = [x].
Related