Learn Python Series (#5) - Handling Lists Part 1

Learn Python Series (#5) - Handling Lists Part 1

python_logo.png

What Will I Learn?

  • You will learn how to create lists, via various ways,
  • how to (shallow) copy them in various ways with varying intended behaviour depending on the goal of your program code,
  • how to access list element values,
  • how to modify those values,
  • various techniques on adding elements to a list.

Requirements

  • A working modern computer running macOS, Windows or Ubuntu
  • An installed Python 3(.6) distribution, such as (for example) the Anaconda Distribution
  • The ambition to learn Python programming

Difficulty

Intermediate

Curriculum (of the Learn Python Series):

Learn Python Series (#5) - Handling Lists Part 1

We've already covered a lot of built-in methods regarding sequence data types, which, of course, a list belongs to, meaning a list is able to use those built-in sequence type methods as well. But as is the case with strings, so do lists have a set of dedicated methods (to create, access, modify / update, add, remove and sort). And then there are some more useful Python statements, functions, and techniques that you can use on handling lists, yet we haven't covered them yet. We'll go over most of them in these two Handling Lists episodes.

Creating and copying lists

There are various ways to create a new list, either being empty initially, or filled with elements right away at creation time.

Square bracket [] notation

One commonly used way, is to use the square bracket [] notation.
For example:

# Create an empty list
empty_list1 = []
print(empty_list)
# []

# Create a list filled with some elements
another_list1 = [1, 2, 3]
print(another_list)
# [1, 2, 3]
[]
[1, 2, 3]

list([seq]) method

The list() method is another way to create (or actually: convert to) lists. The list() method (optionally) accepts a sequence (a string or a tuple) as its argument. For example:

# Create an empty list
empty_list2 = list()
print(empty_list2)
# []

# Create a list from string characters
another_list2a = list('string')
print(another_list2a)
# ['s', 't', 'r', 'i', 'n', 'g']

# Create a list from tuple elements
another_list2b = list((1,2,3))
print(another_list2b)
# [1, 2, 3]

# Or pass in a list, which doesn't really make sense...
another_list2c = list([1,2,3])
print(another_list2c)
# [1, 2, 3]
[]
['s', 't', 'r', 'i', 'n', 'g']
[1, 2, 3]
[1, 2, 3]

list.copy()

To copy a list, you could use the = operator. For example:

# First assign one, then the other
a = [9, 8, 7]
b = a
print(a, b)
# [9, 8, 7] [9, 8, 7]

# Or assign both variables at once
x = y = ['a', 'b', 'c']
print(x,y)
# ['a', 'b', 'c'] ['a', 'b', 'c']
[9, 8, 7] [9, 8, 7]
['a', 'b', 'c'] ['a', 'b', 'c']

However, in case you want to modify the first one, you also modify the other one!

PS: the append() method used for these examples, is explained below.

# If we now add another element to `a`,
# we also add the same element to `b`!
a.append(6)
print(a, b)
# [9, 8, 7, 6] [9, 8, 7, 6]
[9, 8, 7, 6] [9, 8, 7, 6]
# PS: strings have different behavior
i = j = 'Hi'
i += '!'
print(i,j)
# Hi! Hi
Hi! Hi

To avoid this "multiple modification" issue, you can use the copy() method to make a so-called shallow copy, like so:

a = [9, 8, 7]
b = a.copy()
print(a,b)
# [9, 8, 7] [9, 8, 7]

a.append(6)
print(a,b)
# [9, 8, 7, 6] [9, 8, 7]
[9, 8, 7] [9, 8, 7]
[9, 8, 7, 6] [9, 8, 7]

Getting (accessing) and setting (updating) existing list element values

Square bracket [] notation

Again square brackets [] can be used to access ("get") element values from an existing list, either by index or slice. This was already discussed in the Intro episode of this Learn Python Series. A brief reminder:

a = ['a', 'b', 'c', 'd', 'e']

# Access by index
print(a[0], a[-1])
# a e

# Access by slice
print(a[0:2], a[2:len(a)])
# ['a', 'b'] ['c', 'd', 'e']
a e
['a', 'b'] ['c', 'd', 'e']

You can also update ("set") element values using square brackets [] notation, either by index to update 1 element, or by sequence (tuple, list, or string) to update multiple elements. Like so:

a = ['a', 'b', 'c', 'd', 'e']

# Update 1 element by index
a[0] = 'z'
print(a)
# ['z', 'b', 'c', 'd', 'e']

# Update multiple elements with a tuple
a[-2:] = ('k', 'l')
print(a)
# ['z', 'b', 'c', 'k', 'l']

# Update multiple elements with a list
a[-2:] = ['i', 'j']
print(a)
# ['z', 'b', 'c', 'i', 'j']

# Update multiple elements with a string
a[-2:] = 'mn'
print(a)
# ['z', 'b', 'c', 'm', 'n']
['z', 'b', 'c', 'd', 'e']
['z', 'b', 'c', 'k', 'l']
['z', 'b', 'c', 'i', 'j']
['z', 'b', 'c', 'm', 'n']

list.index(x[, start[, end]])

The index() method returns the lowest index (= first position) at which value x is found in the list. index() optionally accepts either a start, or start and end argument, both being zero-based indexes, and if they are passed then the returned index, at which the value is found, is calculated from the beginning of the total list rather than from the start argument passed in. In case the x argument cannot be found, index raises a ValueError.

Please regard the following examples:

list_x = [0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0]

# Let's locate the lowest index of value `1`
i = list_x.index(1)
print(i)
# 1

# Let's locate the lowest index of value `1`,
# starting to look at index 5
j = list_x.index(1, 5)
print(j)
# 9

# Let's locate the lowest index of value `1`,
# starting to look at index 5, ending at 8
k = list_x.index(1, 5, 8)
print(k)
# A ValueError is raised, since value `1` 
# can now not be found / returned
'''
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
 in ()
      9 # 9
     10 
---> 11 k = list_x.index(1, 5, 8)
     12 print(k)

ValueError: 1 is not in list
'''

Adding elements to a list

list.append(x)

Adds a new element at the end of the current list. For example:

list1 = [1, 2, 3, 4, 5]

# `append()` adds 1 element to the end of the list
list1.append(6)
print(list1)
# [1, 2, 3, 4, 5, 6]

# of course the example items above do not mean
# `append()` sorts the list...
list1.append(0)
print(list1)
# [1, 2, 3, 4, 5, 6, 0]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 0]

list.extend(iterable)

This works just like append() does, but instead of adding one element, extend() expects an iterable, for example another list, which includes 1 or more elements, and adds those to the current list. For example:

list2 = [1,2,3]

# Add a list to the current list
list2.extend([4,5,6])
print(list2)
# [1, 2, 3, 4, 5, 6]

# or add a tuple
list2.extend((7,8))
print(list2)
# [1, 2, 3, 4, 5, 6, 7, 8]

# a string is also iterable, let's add that!
list2.extend('Hello!')
print(list2)
# [1, 2, 3, 4, 5, 6, 7, 8, 'H', 'e', 'l', 'l', 'o', '!']
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 'H', 'e', 'l', 'l', 'o', '!']

list.insert(i, x)

If you want to add an element to a list, but not (necessarily) at the end, then use insert(). The i argument is short for the list's index, the position of the list before you want to insert() the element in, and of course x is the element (value) you want add in. For example:

list3 = [1, 2, 3]

# Currently element `1` is at index 0,
# so if we want to insert an element before `1`
# then:
list3.insert(0, 0)
print(list3)
# [0, 1, 2, 3]

# if you want to insert after the end,
# then either use `append()` 
# or:
list3.insert(len(list3), 4)
print(list3)
# [0, 1, 2, 3, 4]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]

List concatenation

Using the + or (short-hand) += operator, you can concatenate (= "glue together") two or more lists, like so:

list_a = [1, 2, 3]
list_b = [4, 5, 6]

# List concatenation can be done like this...
list_c = list_a + list_b
print(list_c)
# [1, 2, 3, 4, 5, 6]

# Or like that...
list_c += list_a
print(list_c)
# [1, 2, 3, 4, 5, 6, 1, 2, 3]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 1, 2, 3]

List repetition

Using the * or (short-hand) *= operator, you can repeat two or more lists, like so:

list_d = [1,2,3]

# List repetition can be done like this...
list_e = list_d * 2
print(list_e)
# [1, 2, 3, 1, 2, 3]

# Or like that...
list_e *= 2
print(list_e)
# [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
[1, 2, 3, 1, 2, 3]
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]

What did we learn, hopefully?

In this episode Handling Lists Part 1 we focused on how to create lists, via various ways, on how to (shallow) copy them in various ways with varying intended behavior depending on the goal of your program code, on how to access list element values, and on how to modify those values, including various techniques on adding elements to a list.

In Handling Lists Part 2 we'll continue with various techniques on how to remove elements from a list, or the entire list itself, on how to use lists as a stack, on how to reorder elements in a list, and we'll cover various ways about how you can enumerate, zip and/or transpose, and loop over (multiple) lists. See you there, hopefully!

Thank you for your time!



Posted on Utopian.io - Rewarding Open Source Contributors

H2
H3
H4
Upload from PC
Video gallery
3 columns
2 columns
1 column
14 Comments