CommonLounge Archive

Python3 Lists (Advanced)

July 26, 2018

You have already learnt about lists in a previous tutorial. In this tutorial, we’re going to dive deeper into Python lists.

Review of lists

Python has a great built-in list type named list. List literals are written within square brackets [ ]. Lists work similarly to strings — use the len() function and square brackets [ ] to access data, with the first element at index 0.

colors = ['red', 'blue', 'green']
print(colors[0])    ## red
print(colors[2])    ## green
print(len(colors))  ## 3 

Assignment with an = on lists does not make a copy. Instead, assignment makes the two variables point to the one list in memory.

colors = ['red', 'blue', 'green']
b = colors   ## Does NOT copy the list 
colors[1] = 'yellow'
print(colors) # ['red', 'yellow', 'green']
print(b)      # ['red', 'yellow', 'green']

The “empty list” is just an empty pair of brackets [ ]. The + works to append two lists, so [1, 2] + [3, 4] yields [1, 2, 3, 4] (this is just like + with strings).

for and in

Python’s for and in constructs are extremely useful, and you have already seen its use with lists. The for construct — for var in list — is an easy way to look at each element in a list (or other collections). Do not add or remove from the list during iteration.

squares = [1, 4, 9, 16]
total = 0
for num in squares:
    total += num
print(total)  ## 30

If you know what sort of thing is in the list, use a variable name in the loop that captures that information such as num, or name, or url. Since python code does not have other syntax to remind you of types, your variable names are a key way for you to keep straight what is going on.

The in construct on its own is an easy way to test if an element appears in a list (or other collection) — value in collection — tests if the value is in the collection, returning True / False.

list = ['larry', 'curly', 'moe']
if 'curly' in list:

The for / in constructs are very commonly used in Python code and work on data types other than list, so you should just memorize their syntax. You may have habits from other languages where you start manually iterating over a collection, where in Python you should just use for / in.

You can also use for / in to work on a string. The string acts like a list of its chars, so for ch in s: print(ch) prints all the chars in a string.

List Methods

Here are some other common list methods.

list.append(elem) — adds a single element to the end of the list. Common error: does not return the new list, just modifies the original.

list = ['larry', 'curly', 'moe']
list.append('shemp')         ## append elem at end

list.insert(index, elem) — inserts the element at the given index, shifting elements to the right.

list = ['larry', 'curly', 'moe']
list.insert(0, 'xxx')        ## insert elem at index 0

list.extend(list2) adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend().

list = ['larry', 'curly', 'moe']
list.extend(['yyy', 'zzz'])  ## add list of elems at end

list.index(elem) — searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear (use in to check without a ValueError).

list = ['larry', 'curly', 'moe']
print(list.index('curly'))   ## 1

list.remove(elem) — searches for the first instance of the given element and removes it (throws ValueError if not present)

list = ['larry', 'curly', 'moe']
list.remove('curly')         ## search and remove that element

list.pop(index) — removes and returns the element at the given index. Returns the rightmost element if index is omitted (roughly the opposite of append()).

list = ['larry', 'curly', 'moe']
list.pop(1)                  ## removes and returns 'curly'

list.sort() — sorts the list in place (does not return it). (The sorted() function shown below is preferred.)

list = ['larry', 'curly', 'moe']
list.sort()                 ## sorts the list

list.reverse() — reverses the list in place (does not return it)

list = ['larry', 'curly', 'moe']
list.reverse()                 ## reverses the list

Notice that these are methods on a list object, while len() is a function that takes the list (or string or whatever) as an argument.

Common error: note that the above methods do not return the modified list, they just modify the original list.

list = [1, 2, 3]
print(list.append(4))   ## NO, does not work, append() returns None
## Correct pattern:
list = [1, 2, 3]
print(list)  ## [1, 2, 3, 4]

List Comprehensions

List comprehensions are a more advanced feature which is nice for some cases but is not needed for the exercises and is not something you need to learn at first (i.e. you can skip this section). A list comprehension is a compact way to write an expression that expands to a whole list. Suppose we have a list nums [1, 2, 3, 4], here is the list comprehension to compute a list of their squares [1, 4, 9, 16]:

nums = [1, 2, 3, 4] 
squares = [ n * n for n in nums ]   ## [1, 4, 9, 16]

The syntax is [ expr for var in list ] — the for var in list looks like a regular for-loop, but without the colon :. The expr to its left is evaluated once for each element to give the values for the new list. Here is an example with strings, where each string is changed to upper case with '!!!' appended:

strs = ['hello', 'and', 'goodbye']
shouting = [ s.upper() + '!!!' for s in strs ]
print(shouting) ## ['HELLO!!!', 'AND!!!', 'GOODBYE!!!']

You can add an if test to the right of the for-loop to narrow the result. The if test is evaluated for each element, including only the elements where the test is True.

## Select values <= 2
nums = [2, 8, 1, 6]
small = [ n for n in nums if n <= 2 ] 
print(small) ## [2, 1]
## Select fruits containing 'a', change to upper case
fruits = ['apple', 'cherry', 'banana', 'lemon']
afruits = [ s.upper() for s in fruits if 'a' in s ]
print(afruits) ## ['APPLE', 'BANANA']


In this tutorial, we covered a number of advanced topics in lists:

  • Review of lists
  • for and in
  • List Methods
  • List Comprehensions

Content was originally based on, but has been modified since. Licensed under CC BY 3.0. Code samples licensed under the Apache 2.0 License.

© 2016-2022. All rights reserved.