Python list (insert, append, del, clear)

Today we are going to talk about a wonderful list! So first how do you make one? You can make one by doing this "list = []" which will make just an empty list. But if you print it, it will say "[]" because it is empty. well, how do you add something to it? You can just put them in and separate them with a comma if they are integer. 


So like this:

list = [1, 4, 6, 7]

print(list)


Outcome: 

[1, 4, 6, 7]


So it is pretty good. But how do you delete one of the numbers? You can use "del list[0]" which will delete the first number of the list. (remember  that python starts from 0) Now that we learned how to delete, why don't we learn how to add? You can use append which will add a number at the end, or you can use the insert to add a number or character where you want. 

So if you use append, it will be like this

list = [1, 4, 6, 7]

print(list)

list.append(3)

print(list)

Outcome: 

[1, 4, 6, 7]

[1, 4, 6, 7, 3]


But if you use insert, it will be like this:

list = [1, 4, 6, 7]

print(list)

list.insert(2, """ where you want """ 3 """number that you are going to add""")

print(list)

Outcome: 

[1, 4, 6, 7]

[1, 4, 3, 6, 7]

So now you know how to add and delete let's learn how to define the length of the list. You can use "len(list)"

So an example would be:

list = [1, 3, 5, 7, 8]

print(len(list))

Outcome:

5

And lastly, there is clear, which basically clears all the integers or characters in the list. 

So you know most about the list, but did you know that you can make an inventory system with a list? Try making one, it isn't that hard! I will be back with a more helpful tutorial/lesson next time!

Comments