Making a list

So far we’ve talked about numbers, strings and Booleans where each variable just stores one thing at a time. What happens if we want to manage a shopping list, or a list of students in my class… and I want to be able to manage that entire list of things together? Python allows us to create lists!

Here are three lists:

primes = [1, 2, 3, 5, 7, 11, 13, 17, 19, 23]
vowels = ["A", "E", "I", "O", "U"]
starwars = ["Luke", "Han", "Leah", "Obi-wan", "Yoda", "Rey", "Finn"]

The two key tips to making a list: Python knows it is a list because of the square brackets! Items in a list are separated by commas!

Try the following to work out how the various commands behave.

print( len( starwars ) )
print( starwars[0] )
print( starwars[1] )
print( starwars[2] )
print( starwars[-1] )
print( starwars )

After doing the above, can you guess what this will do?

starwars.append("Darth Vader")
print( len( starwars ))
print( starwars[-1] )
print( starwars )

We can also use the “in” comparison test we used for strings

print( "r2d2" in starwars )

What command would make that print True?

What would these do?

print( starwars[0:2] )
print( starwars[1:3] )
print( starwars[:3] )
print( starwars[3:] )

How will this behave?

starwars.sort()
print( starwars )

Other tricks that are useful when we have lists of numbers:

minimum = min(primes)
maximum = max(primes)
print("The minimum was ",minimum," and the maximum was ",maximum)

Looping through a list

So we have these things called lists… what if we want to run some code on every item in a list? Would I be asking the question if it couldn’t be done?! :-p

In the same way we test to see if a value exists inside a list, we can use the for statement to allow us to run code for each value in that list.

starwars = ["Luke", "Han", "Leah", "Obi-wan", "Yoda", "Rey", "Finn"]
for person in starwars:
    print( "Hello "+person )

We can combine the “for in” with the “if in” functionality to see if each value of one list appears in a second list. Example:

starwars = ["Luke", "Han", "Leah", "Obi-wan", "Yoda", "Rey", "Finn"]
skywalkers = ["Luke", "Leah"]
for person in starwars:
    if person in skywalkers:
        print( person+" is a Skywalker")
    else:
        print( person+" is not a Skywalker")
print("all done!")

List functions

Splitting a string

We split strings the hard way before because we hadn’t learnt about lists, but now we can use the easy method known as the split() function.

birthday = input("Please enter your date of birth as dd/mm/yyyy : ")
parts = birthday.split("/")
print("Your day of birth is ", parts[0])
print("Your month of birth is ", parts[1])
print("Your year of birth is ", parts[2])

Joining a list together

Just as we can split a string into a list, we can join it back together again too.

addressList = ["Chemin de la Grangette 2","1052 Le Mont-sur-Lausanne","Switzerland"]
newAddress = ", ".join(addressList)
print(newAddress)

Appending an item to a list

beatlesMembers = ["John", "Paul", "George"]
beatlesMembers.append("Ringo")

Deleting an item from a list

beatlesMembers = ["John", "Paul", "George", "Ringo"]
beatlesMembers.remove("Ringo")

Delete an item using it’s index number.

beatlesMembers = ["John", "Paul", "George", "Ringo"]
beatlesMembers.pop(1)   # will remove the 2nd value (start counting from zero)
print(beatlesMembers)   # ["John", "George", "Ringo"]

Lists and loops exercises

Tip: The following code will allow you to type a space separated list of integers, and convert it into a Python list variable for you.

usertyped = input("Type some integers with a space between each: ")
mylist = [int(str) for str in usertyped.split()]
  1. Write a Python program to sum all the items in a list.

  2. Write a Python program to get the largest number from a list.

  3. Write a Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings.

  4. Write a Python program to remove duplicates from a list.

  5. Write a Python function that takes two lists and returns True if they have at least one common member.

  6. Write a Python program to print a specified list after removing the 0th, 4th and 5th elements.

    Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow'] Expected Output : ['Green', 'White', 'Black']

  7. Write a Python program to print the numbers of a specified list after removing even numbers from it.

  8. Write a Python program to shuffle a list representing a deck of cards and print the first 5 items from the list as a dealer issuing cards. For extra credit, remove each item after you print it (as the card is no longer in the dealers hand). Sample code containing a deck of cards list is provided at the bottom of the page.

  9. Write a Python program to generate and print a list of first and last 5 elements where the values are square of numbers between 1 and 30 (both included).

  10. Given two lists, write a Python program to print the items that are not in both lists.

  11. Write a Python program to append the items from one list to a second list.

  12. Write a Python program to select an item randomly from a list, which is then removed from the original list so it can’t be re-drawn (just like a deck of cards scenario)

  13. Write a Python program to get the frequency of the elements in a list.

  14. Write a Python program to check whether a list contains a sublist.

  15. Write a Python program for computing primes upto 1000.

    Hint: You will probably want a for-loop inside another for-loop.

    Note: One possible strategy is known In mathematics as the Sieve of Eratosthenes which is illustrated below.

    Sieve Of Eratosthenes Animation

  16. Write a Python program to implement Ceasars Cipher which was famously one of the first methods of sending cryptic messages. It involves using a simple letter substitution. The example below moves each letter by 3 positions. (Remember to ensure that xyz wrap around to abc)

    message in: "attack the castle" message out: "dwwdfn wkh fdvwoh"

  17. Building on the deck of cards scenarios again. Can you start with a list of a deck of cards, randomise it, and then draw 5 cards for each of 5 players, removing each card from the main deck as you do. So you will start with one “master” list and end up with the leftovers in the master list, and 5 lists of 5 cards each.


Deck of cards list for question 8

cards = ['Ace of clubs', '2 of clubs', '3 of clubs', '4 of clubs', '5 of clubs', '6 of clubs', '7 of clubs', '8 of clubs', '9 of clubs', '10 of clubs', 'Jack of clubs', 'Queen of clubs', 'King of clubs', 'Ace of diamonds', '2 of diamonds', '3 of diamonds', '4 of diamonds', '5 of diamonds', '6 of diamonds', '7 of diamonds', '8 of diamonds', '9 of diamonds', '10 of diamonds', 'Jack of diamonds', 'Queen of diamonds', 'King of diamonds', 'Ace of hearts', '2 of hearts', '3 of hearts', '4 of hearts', '5 of hearts', '6 of hearts', '7 of hearts', '8 of hearts', '9 of hearts', '10 of hearts', 'Jack of hearts', 'Queen of hearts', 'King of hearts', 'Ace of spades', '2 of spades', '3 of spades', '4 of spades', '5 of spades', '6 of spades', '7 of spades', '8 of spades', '9 of spades', '10 of spades', 'Jack of spades', 'Queen of spades', 'King of spades']

Sources

Questions sourced from: https://www.w3resource.com/python-exercises/list/ (note: please don’t just steal the solutions from this site. Most of their solutions use techniques I haven’t taught you yet anyway, so would (a) confuse you and (b) be a give away you didn’t do it yourself and (c) defeat the point of learning by solving. Instead, I suggest you work with your neighbours and try to figure out the solutions together!)

Sieve Of Eratosthenes Animation By SKopp at German Wikipedia - Own work, Original image at Image:Animation_Sieve_of_Eratosth.gif, CC BY-SA 3.0, https://commons.wikimedia.org/w/index.php?curid=2810935