Manipulating Lists

Lists are very flexible. There are many built-in functions and methods you can use to manipulate lists.

List Methods

append(): adds an item to the end of an existing list.

Note: A method is also a function, but defined for a class. To call a method on an object (an instance of that class), use the dot notation. e.g. lst.append().

Example:

num = [1, 2, 3]

# add an item
num.append(8)
print(num)           # [1, 2, 3, 8]

append() to an empty list

You can create a new list by appending elements to an empty list:

my_lst = []

for i in range(5):
    my_lst.append(i * i)

print(my_lst)    # [0, 1, 4, 9, 16]

'add' two lists together

You can make a new list by adding two or more lists together.

lst1 = [1, 2, 3]
lst2 = [6, 7, 8, 9]
lst3 = lst1 + lst2

print(lst3)    # [1, 2, 3, 6, 7, 8, 9]

The result from "add" operation is a new list (lst3). The existing lists (lst1 and lst2) are not changed. Compare to append(), which modifies an existing list object.

'multiply' a list by a number

Multiplying a list with a number creates a new list that repeats the existing list:

my_lst = [1,8]
result = my_lst * 3

print(result)    # [1, 8, 1, 8, 1, 8]

More List Methods

lst.remove(item): removes the first occurrence of an item from the list
lst.pop(): removes and returns the last item in the list
lst.index(item): finds the index of the first occurrence of an item
lst.insert(indexNumber, newItem): inserts an item at a specific index
lst.reverse(): reverses the order of items in a list
lst.sort(): sorts the items in list in ascending order of value

Here are some examples:

l = [2, 3, 4, 5, 6, 7, 8]
l.remove(7)   
print(l)         # [2, 3, 4, 5, 6, 8]
l.pop()    
print(l)         # [2, 3, 4, 5, 6]
l.insert(2, 10)        # insert 10 at index 2  
print(l)               # [2, 3, 10, 4, 5, 6]
m = l.index(4)    
print(m)               # 3 (number 4 is at index 3)

Demo reverse() and sort() methods in CodeCraft

For the next two list methods, reverse() and sort(), let's use CodeCraft to demo the effects:

# original list, white columns
t = [2, 4, 1, 8, 5, 6, 7]

for i in range( len(t) ):
    column_m(i, -20, t[i], 15)      # white 

# Reverse items in the list, shift to the right, purple
t.reverse()   

for i in range(len(t)):
    column_m(i + 8, -20, t[i], 55)   

# sort items in list, shift to the right, pink 
t.sort()

for i in range(len(t)):
    column_m(i + 18, -20, t[i], 54 )

As you can see below, the purple columns mirror the white columns, and the pink columns represent the list sorted in ascending order.

List functions

The following functions are not defined in the List class so you don't use dot notation with them. Instead, the object is passed in as a parameter.

max() and min()

Besides the len() function, max() and min() are also Python built-in functions frequently used with lists. They return the item from a list with the maximum or minimum value.

Example:

s = [5, 3, 12, 7, 2, 8]
print('max value: ', max(s))      
print('min value: ', min(s))

Console result:

max value: 12
min value: 2

Generate a list from range()

We have used the range(start, stop, step) function in for loop before, but they can also be used to generate lists of numbers. You can convert the result of the range() function into a list, similar to how a string is converted into integer:

n = list(range(5))
print(n)        # [0, 1, 2, 3, 4]

m = list(range(1, 10, 2))
print(m)        # [1, 3, 5, 7, 9]
CodeCraft Demo

Let's build white columns to represent the numbers in the list, then highlight the maximum value in red and minimum value in green.

# original list s, white columns
for i in range( len(s) ):
    column_m(i, -20, s[i], 15 )              

# maximum value, red
column_m(s.index(max(s)), -20, max(s), 13)    

# minimum value, lime green        
column_m(s.index(min(s)), -20, min(s), 8)

Note: s.index(min(s)) finds the minimum value in the number list min(s), then return the index of that minimum element.

results matching ""

    No results matching ""