Skip to content

Programming Concepts 3: Lists

Nicholas DiBari edited this page Jan 18, 2018 · 1 revision

Lists

Lists are the way to store a collection of variables in Python. If you've used an array in C++, lists work very much the same way. They are 0-indexed, meaning the first element in the list is referred to by the [0] position in the list. They are initialized using the [] operator, and can be either assigned empty or populated with elements. They can store a variety of data types at once, meaning you can store string, integers, and other objects in the same list just fine.

>>> myList = []  # Start with an empty list
>>> len(myList)  ## Returns the number of elements in the list
0
>>> myList = ['apple', 'banana', 2]  # Start with a populated list
>>> len(myList)
3
>>> # Careful! Not the first element in the list, but the element at position 1
>>> print(myList[1])
banana
>>> print(myList[0])
apple

To change the value stored in a list index, you can assign the index of the list to a new value. To add another element to the list, you can use the append built in method for strings. This will add the element to the end of the list. If you want to put the element in a different position, you can use the insert built in to specify an index to put the new element in:

>>> # From example list above
>>> myList[0] = 'grapes'
>>> myList
['grapes', 'banana', 2]
>>> myList[2] += 1
>>> myList
['grapes', 'banana', 3]
>>> myList.append('kiwi')  # Will assign to index 4
>>> len(myList)
4
>>> myList
['grapes', 'banana', 3, 'kiwi']
>>> # insert 'strawberries' into index 1
>>> # slide every element one index higher 
>>> myList.insert(1, 'strawberries')
['grapes', 'strawberries', 'banana', 3, 'kiwi']

Beyond specifying a specific index in a list, you can "slice" the list by passing a range of values:

>>> dopeList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> dopeList[3]
3
>>> # Return elements from index 3 inclusive to index 6 exclusive
>>> dopeList[3:6]
[3, 4, 5]
>>> # Return elements from index 0 inclusive to index 4 exclusive
>>> dopeList[:4]
[0, 1, 2, 3]
>>> # Returns elements from index 2 inclusive to the end of the list
[2, 3, 4, 5, 6, 7, 8, 9]
>>> # Returns whole list
>>> dopeList[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

You can join two lists together with the + operator like so:

>>> list1 = ['My', 'name', 'is']
>>> list2 = ['Kevin']
>>> list3 = list1 + list2
>>> list3
['My', 'name', 'is', 'Kevin']

You can remove elements from the list using the del keyword, if you know the index of the element. Note that if you try to delete an index with no value, an IndexError is raised:

>>> # From example list above
>>> del list3[3]
>>> list3
['My', 'name', 'is']
>>> del list3[3]  # No more element in this index!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range

If you want to remove a value from the list, but you don't know the index of the value, you can use the built in remove method lists have. Note that remove will raise a ValueError if the value is not found:

>>> newList = ['socks', 'mittens', 'hat', 'gloves', 'shorts']
>>> newList.remove('shorts')
>>> newList
['socks', 'mittens', 'hat', 'gloves']
>>> newList.remove('jacket')  # !!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list

If you want to check if an value is in a list, you can use the in built in to check if the value you pass it is present in the list:

>>> admins = ['Nick', 'Fry', 'Morty']
>>> 'Nick' in admins
True
>>> 'Bender' in admins
False
>>> 'Hacker' not in admins
True  # hopefuly...

Clone this wiki locally