Python pt.2 (how to add or delete stuff from lists)

Python pt.2 (how to add or delete stuff from lists)

By ZeusXx | Python introduction | 16 Apr 2021


 

6b09655b3c2a6bc16dff9e91cc7993f136271454544838a766129a3b73b0b1ad.png

 

Today I will teach you how to insert stuff in to list or how to delete stuff from the list.

So first we need to have a list and it is simple to make!

workdays = ["monday","tuesday","thursday","firday","saturday"]

So here is our list, first to make a list you will need a name for that list, in this example its workdays, As you can see it's missing a day and if we wanted to add that day to the list we would have to  use this:

workdays = ["monday","tuesday","thursday","firday","saturday"]
workdays.insert(2, "wednesday")

So with this we are inserting Wednesday into slot number 2, how this strip of code works is really simple, first, you need the name of the list and then you have to specify what exactly you want to do with that list, in this example we want to insert so we put in the insert command.

Then in the brackets you first have to specify what slot you want to add something after that you add the verb or whatever you want to add to the list.

After that you can print your list of things:

workdays = ["monday","tuesday","thursday","firday","saturday"]
workdays.insert(2, "wednesday")

print(workdays)

And that will print your new list of things!

Now if you made a mistake and added something that's now supposed to be there you can simply remove it like this:

workdays = ["monday","tuesday","wednesday","thursday","firday","saturday"]

del workdays [workdays.index("wednesday"): ]

So the first keyword here is what you will be doing to the list, you will be deleting something from the list ( Del ) but just that alone would delete the whole list so you have to specify what you will be deleting in this case it will be the index Wednesday.

Then you can print your list again without the Wednesday index in it!

workdays = ["monday","tuesday","thursday","firday","saturday"]
workdays.insert(2, "wednesday")

del workdays [workdays.index("wednesday"): ]

print(workdays)

And There you go you have just learned how to add stuff to lists and how to remove stuff from lists!

 

 

How do you rate this article?


2

0


Python introduction
Python introduction

Python one of the most popular computer languages, and it is the easiest one to learn! so the quick explanation would be that it can do everything ... just badly or not as good as other programming languages. the most simple command you can learn is the print ("example") command it is the starting command everyone need to learn.

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.