05 Lists, Tuples and SetsBy: Tuur Muyldermans question Questions 5.1 IntroductionSo far weve 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. In section 8 we will also discuss dictionaries. By means of a brief summary, already in this stage; there are four collection data types in Python:
They are useful in different circumstances and each data-type has its own advantage. On a small-case example this might not be noticable, however on a larger scale using the right data-type can save you a lot of time. 5.2 Lists and rangeYou can make your own Python list from scratch: myList = [5,3,56,13,33]
myList
You can also use the range() function. Try this: myList = list(range(10))
myList
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. Note that Python always starts counting from 0. The command above will give you a series of integers starting from 0 and stopping at the number you defined, however with this number not included in the list. Hence, it stops at 9. You can start from a different number as well: myList = list(range(3,12))
myList
or increase the step size (the default is step size is 1): myList = list(range(1,12,2))
myList
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. Some examples of methods are:
myList = [] # Create an empty list
myList.append(5) # Add a single value to the back of the list
myList
myList.insert(0,9) # Insert a value in the list at index (element position) 0
myList
myList.extend([99,3,5]) # Extend the list with another list
myList
myList[0] # Return the first element in the list (counting starts at zero)
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 {}".format(myRemovedElement))
myList
myList.sort() # You can sort the elements in a list - this will change their order
myList
myList.reverse() # Or reverse the order of the list
myList
You can also select a slice from a list - this will give you a new list: myList = list(range(15))
myListSlice = myList[3:6]
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:
myList = list(range(1,15))
myList
myList.count(10) # Will count the amount of times the value 10 occurs in this list
myList.count("A") # This always works, and will return 0 if nothing is found
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!!!
5.3 TuplesSimilar 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 dont change, like (part of) the alphabet for example: myTuple = ("A","B","C","D","E","F")
myTuple
Important to remember is that if you create a tuple with one value you have to use a comma: myTuple = ("My string",)
myTuple
myWrongTuple = ("My string") # The brackets here don't do anything.
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 = list(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)
myTupleLength
Tuples are faster during iteration procedures due to their immutability.
5.4 StringsStrings 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."
myString[0:5] # Take the first five characters
myString.count("e") # Count the number of 'e' characters
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. "
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!
A list with all string methods and a full description can be found in the Python documentation, or simply type dir(myString) dir(myString)
5.5 SetsVery useful as well are sets. These are unordered and unindexed (so the order in which you put in elements doesnt matter), and it is much easier to compare them to each other. Because sets cannot have multiple occurrences of the same element, it makes sets highly useful to efficiently remove duplicate values from a list or tuple and to perform common math operations like unions and intersections. Source: https://www.learnbyexample.org/python-set/ 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))
dir(mySet1)
The principle of using intersection and union is the same as the Venn diagrams you probably saw in school You can also make a set out of a string: myString = "This is a sentence."
myLetters = set(myString)
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.
Useful literatureFurther information, including links to documentation and original publications, regarding the tools, analysis techniques and the interpretation of results described in this tutorial can be found here. congratulations Congratulations on successfully completing this tutorial! |