Salvatore Lopiparo

Senior 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:

1
>>> grocery_list = []

Or define a list with things in it:

1
>>> 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.

1
2
3
4
5
6
>>> hit_list[0]
'Frankie'
>>> hit_list[1]
'Jimmy'
>>> hit_list[5]
'3-Fingers Tony'

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

1
2
3
>>> 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…

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

or the front…

1
2
3
4
>>> hit_list.pop(0)
'Frankie'
>>> 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.

1
2
3
4
5
>>> 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:

1
2
3
>>> 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.

1
2
3
4
>>> 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.

Leave a Reply