Python training exercise 4
Contents
Introduction
So far we've seen variables where you essentially assign a value to a name that you can use in the program. It is also possible to assign groups of values to a name, in Python these are called lists and tuples - variables that contain multiple values in a fixed order. Python also has sets, which are also variables that contain multiple values, but in no particular order. They are useful in different circumstances, which we'll try to explain below.
Exercises
range() and lists
You can make your own Python list from scratch:
myList = [5,3,56,13,33] print(myList)
You can also use the range() function. Try this:
print(list(range(10)))
You should get the following output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]. This is a list of integers - you can recognize a list by the square [ ] brackets. The range command 'counts' from 0 to the number you give it. You can start from a different number as well:
print(list(range(1,11)))
or increase the step size (the default is step size is 1):
print(list(range(1,20,2)))
An important feature of lists is that they are flexible - you can add and remove values, change the order, ... . You can do such modifications by calling a method from the list itself:
myList = [] # Create an empty list myList.append(5) # Add a single value to the back of the list print(myList) myList.insert(0,9) # Insert a value in the list at index (element position) 0 print(myList) myList.extend([99,3,5]) # Extend the list with another list print(myList) print(myList[0]) # Return the first element in the list (counting starts at zero) print(myList[2]) # Return the third element in the list myRemovedElement = myList.pop(3) # Remove the fourth element in the list and return it print("I removed {}".formatmyRemovedElement)) print(myList) myList.sort() # You can sort the elements in a list - this will change their order print(myList) myList.reverse() # Or reverse the order of the list print(myList)
You can also select a slice from a list - this will give you a new list:
myList = range(15) myListSlice = myList[3:6] print(myListSlice) myListCopy = myList[:] print(myListCopy) print(myList[-4:]) # This will select the fourth-last to the last element in the list
There are two other methods you can use on lists, .index() and .count():
myList = range(1,15) print(myList) print(myList.count(10)) # Will count the amount of times the value 10 occurs in this list print(myList.count("A")) # This always works, and will return 0 if nothing is found print(myList.index(10)) # Will give the index of the element with value 10 - in this case 9 because the list index starts at 0. print(myList.index("A")) # This will crash the program - the value to look for has to be present in the list!!!
Take the list [54,56,2,1,5223,6,23,57,3,7,3344], sort it in reverse order (largest value first) and print out the third value. [click on show more for answer) |
---|
myList = [54,56,2,1,5223,6,23,57,3,7,3344] myList.sort() myList.reverse() print(myList[2]) The first element is at index 0, the third at index 3! |
tuple
Similar to lists are tuples - essentially they are the same, except that a tuple cannot be modified once created. This can be useful for values that don't change, like (part of) the alphabet for example:
myTuple = ("A","B","C","D","E","F") print(myTuple)
Important to remember is that if you create a tuple with one value you have to use a comma:
myTuple = ("My string",) print(myTuple) myWrongTuple = ("My string") # The brackets here don't do anything. print(myWrongTuple)
A tuple is indicated by round brackets ( ). You can interconvert between lists and tuples by using list() and tuple():
myTuple = ("A","B","C","D","E","F") myList = range(10) myNewTuple = tuple(myList) myNewList = list(myTuple) print("{} and {}".format(myList, myNewTuple)) print("{} and {}".format(myTuple, myNewList))
You can find out the length (number of elements) in a list or tuple with len():
myTuple = ("A","B","C","D","E","F") myTupleLength = len(myTuple) print(myTupleLength)
Start with the tuple ('a','B','c','D','e','F'), sort it, take the fourth value out, and print the result. [click on show more for answer) |
---|
myTuple = ('a','B','c','D','e','F') myList = list(myTuple) myList.sort() print ("Removing {}".format(myList.pop(3))) print ("Result is {}".format(str(tuple(myList)))) Note that upper case characters are sorted first - they have lower character values when being sorted than the lower case ones. |
strings are a bit like lists and tuples
Strings are really a sequence of characters, and they behave similar to lists:
myString = "This is a sentence." print(myString[0:5]) # Take the first five characters print(myString.count("e")) # Count the number of 'e' characters print(myString.index("i")) # Give the index of the first 'i' character
You cannot re-assign strings as you do with lists though, the following example does not work:
myString = "This is a sentence." myString[4] = ' not'
Note that strings have many other methods that we haven't discussed yet. Here are some of the most useful:
myString = " This is a sentence with spaces. " print(myString.upper()) # Upper-case all characters print(myString.lower()) # Lower-case all characters print(myString.strip()) # Strip leading and trailing spaces/tabs/newlines print(myString.split()) # Split the line into elements - default is splitting by whitespace characters print(myString.replace(' is ',' was ')) # Replace ' is ' by ' was '. Spaces are necessary, otherwise the 'is' in 'This' will be replaced!
For a full description, see the Python documentation.
Ask the user for two words, then check whether they are the same (upper or lower case should not matter), if not check whether they have the same first letter (again case should not matter). If not, then print their length. [click on show more for answer) |
---|
firstWord = input("Give first word:") secondWord = input("Give second word:") if firstWord.upper() == secondWord.upper(): print("Words are the same (ignoring case).") elif firstWord[0].upper() == secondWord[0].upper(): print("Words share the same first letter (ignoring case).") else: print("Word lengths are {} and {}".format((len(firstWord),len(secondWord)))) |
sets
Very useful as well are sets. These are not ordered (so the order in which you put in elements doesn't matter), and it is much easier to compare them to each other. The principle is the same as the Venn diagrams you probably saw in school... you initialise them by using set() on a list or tuple:
mySet1 = set(range(10)) mySet2 = set(range(5,20)) print(mySet1) print(mySet2) mySet.add(5) # Elements in a set are unique - the set will not change because it already has a 5 print(mySet1.intersection(mySet2)) print(mySet1.union(mySet2))
You can also make a set out of a string:
myString = "This is a sentence." myLetters = set(myString) print(myLetters) # Note that an upper case T and lower case t are not the same!
There are more things you can do with sets which we will not go into here, see the Python sets documentation for more information.
Which letters are shared between the words "perspicacious" and "circumlocution"? [click on show more for answer) |
---|
firstWord = "perspicacious" secondWord = "circumlocution" firstLetterSet = set(firstWord) secondLetterSet = set(secondWord) print(firstLetterSet.intersection(secondLetterSet)) |