List manipulation in Python

Goal for this assignment

The goal for this assignment is to learn to use the various methods for Python's list data type.

Your name

// put your name here!

Part 1: working with lists in Python

A list in Python is what is known as a compound data type, which is fundamentally used to group together other types of variables. It is possible for lists to have values of a variety of types (i.e., integers, strings, floating-point numbers, etc.) but in general people tend to create lists with a single data type. Lists are written as comma-separated values between square brackets, like so:

odd_numbers = [1, 3, 5, 7, 9]

and an empty list can be created by using square brackets with no values:

empty_list = []

The number of elements of a list can be found by using the Python len() method: len(odd_numbers) would return 5, for example.

Lists are accessed using index values: odd_numbers[2] will return the 3rd element from the beginning of the list (since Python counts starting at 0). In this case, the value returned would be 5. Using negative numbers in the index gives you elements starting at the end. For example, odd_numbers[-1] gives you the last element in the list, and odd_numbers[-1] gives you the second-to-last number.

Lists can also be indexed by slicing the list, which gives you a sub-set of the list (which is also a list). A colon indicates that slicing is occurring, and you use the syntax my_array[start:end]. In this example, start is the index where you start, and end is the index after the one you want to end (in keeping with the rest of Python's syntax). If start or end are blank, the slice either begins at the beginning of the list or continues to the end of the list, respectively.

You can also add a third argument, which is the step. In other words, my_array[start:end:step] goes from start index to the index before end in steps of step. More concretely, my_array[1,6,2] will return a list composed of elements 1, 3, and 5 of that list, and my_array[::2] returns every second element in the list.

IMPORTANT: you can do all of these things in Numpy, too!

Some examples are below:


In [ ]:
even_numbers = [2, 4, 6, 8, 10, 12, 14]

s1 = even_numbers[1:5]  # returns the 2nd through 4th elements
print("s1:", s1)

s2 = even_numbers[2:]  # returns the 3rd element thorugh the end
print("s2:", s2)

s3 = even_numbers[:-2]   # returns everything but the last two elements
print("s3:", s3)

s4 = even_numbers[1:-2]  # returns everything but the first element and the two elements on the end
print("s4:", s4)

s5 = even_numbers[1:-1:2]  # returns every other element, starting with the second element and ending at the second-to-last
print("s5:", s5)

s6 = even_numbers[::-1] # starts at the end of the list and returns all elements in backwards order (reversing original list) 
print("s6:", s6)

Now, try it yourself!

Using the array below, create and print out sub-arrays that do the following:

  1. print out the first four elements (a-d)
  2. print out the last three elements (g-i)
  3. starting with the second element, print out every third element (b, e, h)

In [ ]:
some_letters = ['a','b','c','d','e','f','g','h','i']

# put your code here!

print("1. first four elements:", some_letters[:4])
print("2. last three elements:", some_letters[-3:])
print("3. every third element, starting from 2nd:", some_letters[1::3])

Part 2: list methods in Python

There are several useful methods that are built into lists in Python. A full explanation of all list methods can be found here. However, the most useful list methods are as follows:

list.append(x) - adds an item x to the end of your list.

list.extend(L) - extends the list by adding all items in the given list L. If you try to use the append() method, you will end up with a list that has an element that is another list - this creates a single, unified list made up of the two original lists.

list.insert(i, x) - insert item x at index position i. list.insert(0,x) inserts at the front of the list

list.pop(i) - removes the item at index i and returns it. If you don't give an index, list.pop() gives you the last item in the list.

list.reverse() - reverse the order of the elements of the list. This happens in place, and doesn't return anything.

An important note about copying lists in Python

You may try to copy a list so you can work with it:

new_list = old_list

However, you'll find that if you modify new_list, you also modify old_list. That's because when you equate lists in the way shown above, you are creating a new list that "points at" the old values. To truly copy a list, you have to do the following:

you are still pointing at the old values, and can modify them. The (weird, but correct) way to copy a list is to say:

new_list = list(old_list)

Now, try it yourself!

Using the arrays below, create new arrays, manipulate them as follows, and then print them out:

  • Create a new array C, which a copy of A, and append the numbers 7 and 8 to the end. (so the elements of C are 1,2,3,4,5,6,7,8)
  • Then remove the third element of C and put it back into the array before the second element from the end (so its elements, in order, are 1, 2, 4, 5, 6, 3, 7, 8)
  • Make a new array D that is a copy of A, and then extend it with the middle three elements of array B, using slicing to get the middle 3 elements of B, (so its elements, in order, are 1, 2, 3, 4, 5, 6, 'b', 'c', 'd').
  • Make a new array E that is a copy of B, reverse the order of its elements, and then remove the first element (so its elements, in order, are 'd', 'c', 'b', 'a').

In [ ]:
A = [1,2,3,4,5,6]
B = ['a','b','c','d','e']

# put your code here!

C = list(A)
C.append(7)
C.append(8)
print("C: ", C)

x = C.pop(2)
C.insert(-2,x)

print("new C:", C)

D = list(A)
D.extend(B[1:-1])

print("D", D)

E = list(B)
E.reverse()
E.pop(0)

print("E:", E)

Assignment wrapup

Please fill out the form that appears when you run the code below. You must completely fill this out in order to receive credit for the assignment!


In [ ]:
from IPython.display import HTML
HTML(
"""
<iframe 
	src="https://goo.gl/forms/jXRNcKiQ8C3lvt8E2?embedded=true" 
	width="80%" 
	height="1200px" 
	frameborder="0" 
	marginheight="0" 
	marginwidth="0">
	Loading...
</iframe>
"""
)

Congratulations, you're done!

Submit this assignment by uploading it to the course Desire2Learn web page. Go to the "Pre-class assignments" folder, find the dropbox link for Day 14, and upload it there.

See you in class!