Salvatore Lopiparo

Software Engineer

Super Simple Python #6 – Lists

Lists in Python are the same thing as they are in every day language: A sequence of items that go together. Usually things in the list are of the same type, like a grocery list or a hit list.

If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!

You can either define an empty list:

>>> grocery_list = []

Or define a list with things in it:

>>> hit_list = ['Frankie', 'Jimmy', 'Gambini', 'Capone', 'Luciana', '3-Fingers Tony', 'Corleone']

If you want to get a specific item in the list, use square brackets and the index of the item. Note that lists start with an index of 0, not 1.

>>> hit_list[0]
>>> hit_list[1]
>>> hit_list[5]
'3-Fingers Tony'

Now let’s say we need to… ahemremove someone from the list.

>>> hit_list.remove('Gambini')
>>> hit_list
['Frankie', 'Jimmy', 'Capone', 'Luciana', '3-Fingers Tony', 'Corleone']

Or, if you prefer to work in order, you can pop them off the back…

>>> hit_list.pop()
>>> hit_list
['Frankie', 'Jimmy', 'Capone', 'Luciana', '3-Fingers Tony']

or the front…

>>> hit_list.pop(0)
>>> hit_list
['Jimmy', 'Capone', 'Luciana', '3-Fingers Tony']

If you want to change an item in the list, simply assign it to an index like you would any other variable.

>>> hit_list[3]
'3-Fingers Tony'
>>> hit_list[3] = "2-Fingers Tony"
>>> hit_list[3]
'2-Fingers Tony'

I’d rather not think about why his name changed.

Let’s say some guy on the internet is making death threats to several high-profile gangsters. Obviously we will need to add someone to the list. You can append them to the end of the list like so:

>>> hit_list.append('Salvatore')
>>> hit_list
['Jimmy', 'Capone', 'Luciana', '2-Fingers Tony', 'Salvatore']

Or, if you’d rather not wait to elimina… I mean put them at the end of the list, we can use insert, passing it the index we want to insert it before. Inserting before 0 will put it in the front.

>>> hit_list.remove('Salvatore')
>>> hit_list.insert(0, 'Salvatore')
>>> hit_list
['Salvatore', 'Jimmy', 'Capone', 'Luciana', '2-Fingers Tony']

I will have to cut this lesson here, as there appears to be a couple of violin salesmen at the door.


Your email address will not be published. Required fields are marked *