Python Lists

top-10-list

Welcome to Lists in Python

A list is a Python data structure that allows programmers to maintain a collection of objects.  Lists are simply a set of values contained in square brackets, with the items separated by commas.

Example:

list1 = [10, 20, 30, 'Math', 'Is', 'Cool']

We access the items in the list using its index (starting with zero) or place in the list.  So list1[3] is Math and list1[1] is 20. Try it.

list1 = [10, 20, 30, 'Math', 'Is', 'Cool']
print(list1[4])  # Is
print(list1[0])  # 0

To find the number of items in a list, use len():

print len(list1)

The statement above would display 6.

Adding and Removing Items to a List

To add items to a list, you can either use the append() method or use concatenation (+).  append() is considered faster.  Both of the following statements add items to our list.

list1.append('Really')
list1 = list1 + 'Seriously'

Our list is now [10, 20, 30, ‘Math’, ‘Is’, ‘Cool’, ‘Really’, ‘Seriously’].

To remove items from a list, we use pop() or remove().  Use pop() if you know the index of the item.  Use remove() if you know the value.  See below:

list1.pop(1)
list1.remove('Really')

Our list is now [10,30, ‘Math’, ‘Is’, ‘Cool’, ‘Seriously’].

Moving Through a List

We can traverse a list with a for statement.  See below:

for stuff in list1:
    print stuff

This code snippet will display the following output:

10
20
30
Math
Is
Cool

Getting a List from the User

We can use raw_input() to accept a list from the user, but it takes a little extra help from the split() method.  See below:

mylist = raw_input('Enter a list: ').split(',')
for stuff in mylist:
    print stuff

When the user enters stuff separated by commas, the split() method, converts the items into a Python list of strings.  Give it a try 🙂

We can use the map function to cast the items in the last as a particular type. For example, if we want our list to be considered integers instead of strings, use the following code:

mylist = raw_input('Enter a list: ').split(',')

mylist = map(int, mylist)

for stuff in mylist:
    print stuff

Comparing Lists

We can use the == operator to compare two lists.  True is returned if the lists are the same, False is returned if the lists are not the same. Try this code:

l = [1,2,3]
m = [1,2,3]
print(l == m)

Other List Methods

The code below shows a few other useful list methods with comments explaining their purpose. You can copy the code and test it out also.

mylist = ['a','b','c','d','e']
mylist.reverse()
print(mylist)

# mylist is now ['e', 'd', 'c', 'b', 'a']

mylist.insert(2,'M')
print(mylist)

# mylist is now ['e', 'd', 'M', 'c', 'b', 'a']

mylist.sort()
print(mylist)

# mylist is now ['M', 'a', 'b', 'c', 'd', 'e'] 
#- (Capitals come before lower case in Python)

Slicing Lists

Slicing a list means grabbing a certain subset of the list. For example, we can select just positions 2 and three with the slice mylist[2:4], where the first number is the starting position and the last number is one more than the last selected position (4 is not included in the slice). Copy the code below into IDLE and test it out.

# Examples of Slices with Python Lists

print('------------------------')
print('Fun With Lists - Slicing')
print('------------------------')
print(' ') # Blank line

mylist = [1,2,'Go','Creek',2013,2014]

print('Original List:')
print(mylist)
print(' ') # Blank line

print('Start at position three and include the remaining positions - mylist[3:]')
print(mylist[3:)
print(' ') # Blank line

print('Start at position 1 and include 2 and 3 but not 4 - mylist[1:4]')
print(mylist[1:4])
print(' ') # Blank line

print('Position -1 is the same as the last one in the list - mylist[-1]')
print(mylist[-1])
print(' ') # Blank line

print('Get the first 2 elements of the list - mylist[:2]')
print(mylist[:2])
print(' ') # Blank line

print('Replace positions 1 - 3 with new items. mylist[1:4] = ...')
mylist[1:4] = ['this','is','new']
print(mylist)
print(' ') # Blank line

print('Replace positions 1 - 3 with only 2 items, changing the length of the list. mylist[1:4] = ...')
mylist[1:4] = ['now','shorter']
print(mylist)
print(' ') # Blank line

Here are some resource links where you can find out more about lists in python:

Exercises

Now for the exercises:

  1. Write a program that accepts a list of numbers from the user and displays them in ascending order (sorted). The user is allowed to enter any number of elements, so you may see 4 numbers or 17. Save the program with the filename yourname-lists-1.py.
  2. Write a program that accepts a list of items from the user, chops off the first and last elements, and then displays the content of the new list. Save the program with the filename yourname-lists-2.py.
  3. Write a program that accepts a list of numbers from the user and displays their sum. (Hint: Use a counter.)  The user is allowed to enter any number of elements, so you may see 4 numbers or 17 numbers. Save the program with the filename yourname-lists-3.py.
  4. Write a program that accepts two lists from the user (as separate raw_input() statements) and then determines if the lists are reverses of each other, displaying either Yes or No. Save the program with the filename yourname-lists-4.py.
  5. Write a program that accepts a list of numbers from the user and then counts the number of odd numbers that are in the list. (Hint: When you divide an odd number by 2, the remainder is 1). Save the program with the filename yourname-lists-5.py.
  6. Extend program 5 above so it displays both the number of even numbers in a list and the number of odd numbers in the list. (You can assume the the list contains only numbers.) Save As the program with the filename yourname-lists-6.py
  7. Write a program that will accept a list of numbers from the user and displays the sum of all the elements up to, but not including the first even number. (Stop when you hit an even.) Save the program with the filename yourname-lists-7.py
  8. Write a program to accept a list from the user. The list can include strings and numbers. If the list has 9 or more elements, replace positions 1 to 7 with [‘Programming’,1]. If the list has from 4 to 8 elements, replace positions 2 and 3 with [‘Python’,’Rules’]. If the list has less than 4 elements, just print the list. Save the program with the filename yourname-lists-8.py