Presentation is loading. Please wait.

Presentation is loading. Please wait.

Python Lists and Sequences

Similar presentations


Presentation on theme: "Python Lists and Sequences"— Presentation transcript:

1 Python Lists and Sequences
Peter Wad Sackett

2 List properties What are lists?
A list is a mutable ordered sequence of objects. Changable. Sequence, shares properties with strings. Any objects, like a mix of strings, numbers, etc. A simple list assignment: primes = list() primes = [2, 3, 5, 7, 11, 13, 17] print (primes[2]) Result is 5 as lists are zero-based like strings. Assignment of an element in a list – only in range. primes[5] = 12

3 Similarities between lists and strings
Strings and lists are both sequences - they work much the same. primes = [2, 3, 5, 7, 11, 13] Length. numberofprimes = len(primes) Addition and multiplication. numbers = primes + [1, 4, 6, 8] numbers = 2 * primes A slice of a list. partprimes = primes[2:4] Advanced slicing. everysecondprime = primes[::2]

4 Examples Counting how many odd numbers are in a list of integers.
randomNumbers = [5, 4, 5, 93, 1, 24, 7] count = 0 for number in randomNumbers: if number % 2 == 1: count += 1 print(”Odd numbers in list:”, count) Increasing all numbers in a list with 1. for position in range(len(randomNumbers)): randomNumbers[position] += 1 Printing the elements of a list – one on each line. randomData = [5, ’Booger’, 5.543, ’Kick, 1, ’flow’, 7] for element in Randomdata: print(element)

5 Changing lists Slice assignment
A slice assignment of a list can be thought of as a two step process: Deletion – the slice specified to the left of = is deleted. Insertion – the new list is inserted where the element where deleted. primes = [1, 2, 3, 5, 8, 9, 10, 13, 19] Deletion of an element. primes [0:1] = [] Inserting element. primes[-1:-1] = [17] Replacing elements. primes[3:6] = [7, 11] Final result: [2, 3, 5, 7, 11, 13, 17, 19]

6 List methods Many of these methods are similar to slice assignment.
primes = [2, 3, 5, 7, 11, 13] Adding one element to the end of the list. primes.append(17) Adding several elements (as list) to the end of the list. primes.extend([19, 23, 29]) Inserting into the list at index position. 4 is inserted here. primes.insert(2, 4) Deleting an element or a slice. del primes[2] Popping an element, default last element. elem = primes.pop() # removing 13 elem = primes.pop(1) # removing 3 Remove the first element from list with this value. primes.remove(11) Clearing a list. This keeps the list but removes the elements. primes.clear()

7 Examples Add the numbers in two lists together in a new list. If one list is longer than the other, just transfer the numbers from the longer list. There are several ways to achieve this. list1 = [5, 4, 5, 93, 1, 24, 7] list2 = [567, 56, 33, 34, 74, 73] # find max list length maxLength = len(list1) if len(list2) > maxLength: maxLength = len(list2) sumList = [0] * maxLength for position in range(len(list1)): sumList[position] += list1[position] for position in range(len(list2)): sumList[position] += list2[position] # Alternative sumList = list() for element in list1: sumList.append(element) if len(sumList) <= position: sumList.append(list2[position]) else:

8 More complex list methods
Reversing a list in place. primes.reverse() Sort a list in place, very powerful, costly, smallest element at top. primes.sort() All elements have to be of the same type to be compared properly. The sort order can be reversed, smallest element at bottom. primes.sort(reverse=True) All elements from the list can be assigned a sort-key, and they will be sorted according to that key instead of their own value. words = [’I’, ’am’, ’Peter’, ’the’, ’Boogyman’] Sorting above, but ignoring case. words.sort(key=str.lower) key has to be assigned a function that takes one argument and returns a value. The built-in function sorted() is similar, but returns a new list.

9 Splitting Splitting a string into a list.
sentence = ’Let there be light’ words = sentence.split() The list words is: [’Let’, ’there’, ’be’, ’light’] split with no arguments splits on whitespace, ignoring leading and trailing whitespace. Very often used. You can also split on specific character(s). commadata = ’Peter,172,78’ mylist = commadata.split(sep=’,’) You can decide to split only at the first separator. mylist = commadata.split(sep=’,’,maxsplit=1) Any split always results in a list – no matter if the result is only 0 or 1 elements.

10 Joining Joining a list of strings into a string, the opposite of split. fairytale = [’Snowwhite’, ’and’, ’the’, ’seven’, ’dwarves’] mystring = ’-’.join(fairytale) Result is ’Snowwhite-and-the-seven-dwarves’ The string (here ’-’) providing the method is the string that joins the elements of the list. Popular choices for strings are ’\n’ and ’ ’. You can print a tab-separated line where the column content is a list of strings, or numbers made into strings, like: print(”\t”.join(number_list)) The methods split() and join() are both string methods, but works with lists.

11 Examples If you create a string of DNA sequence where there is some whitespace in the string and you want to get rid of it, then an easy solution is this; Split the DNA string on whitespace and join it again on empty string. It is a trick. DNA = ”TACGACT TACATG\nATGC GCTCAG\nTACG\tTGATA” DNA = ’’.join(DNA.split()) Transform an input line to list of numbers import sys dataline = input(’Give me a lot of numbers separated by space:’) numbers = list() for element in dataline.split(): try: numbers.append(float(element)) except ValueError: print(”Not all numbers, try again.”) sys.exit(1) numbers.sort() print(”Here are the numbers sorted”) for number in numbers: print(number)

12 Copying lists primes = [2, 3, 5, 7, 11, 13]
Lists are mutable python objects. When assigning one list to a new variable, you are just making a new variable that referes to the same list. Any change made to primes will be made to samelist and vice versa. samelist = primes samelist += [17] print(primes) Result: [2, 3, 5, 7, 11, 13, 17] To make a new different list with the same content as the old do differentlist = primes[:] This is a copy as opposed to the above alias. This has been the source of many errors. More about this later.

13 Examples Returning to the problem of adding the numbers in two lists together; With the new method of copying lists, the problem can be solved as: list1 = [5, 4, 5, 93, 1, 24, 7] list2 = [567, 56, 33, 34, 74, 73] sumList = list1[:] for position in range(len(list2)): if len(sumList) <= position: sumList.append(list2[position]) else: sumList[position] += list2[position]

14 Reading files and lists
When reading a file into a list, there are generally two ways. # Method 1: Classic file reading loop mylist = [] for line in infile: mylist.append(line) # Method 2: Slurping the file in one go with readlines method mylist = infile.readlines() The classic method 1 has the advantage of being able to work on the lines as they come – perhaps you want to remove the newline or maybe you only want part of the line or nor all lines. The slurping method 2 has only the advantage of performance, but if you really need the entire file, then it is quick to do. Be sure that the file is small enough so it can be in memory or an error occurs.

15 The in operator The in operator is very versatile in Python and intentionally mimics our understanding of the word. Used in loops to cover a range or iterable. for i in range(10): for line in file: Used in conditions to check if an item is in a list. if 5 in primes: if codon in (’TGA’, ’TAG’, ’TAA’): Used in conditions to see if a string is a substring of another string. if ’ATG’ in dnasequence: if char in ’ ’: Natural uses with other data types like dictionaries and sets (later). Danger: Has a hidden loop when used with lists. Performance hit.

16 Command line arguments
By importing the sys library, you gain access to sys.argv, the argument vector. It is a list that contains the arguments to the program. The first element in the list is the program name and the following are the arguments. The program ’mynameis.py’ consist of these statements. import sys print(’Your name is’, sys.argv[1]) The result of running the command ’mynameis.py Peter’ is: Your name is Peter

17 Examples The same program as on previous slide, but better. import sys
if len(sys.argv) == 1: print(”You did not supply a name”) else: name = ’ ’.join(sys.argv[1:]) print(’Your name is’, name) Get a file name from command line. if len(sys.argv) != 2: print(”You must supply one file name”) sys.exit(1) try: infile = open(sys.argv[1], ’r’) except IOError: for line in infile: print(line[:-1]) infile.close()

18 Tuples Tuples are immutable lists
Supports all list methods that does not change the list. Assigning tuples, use parenthesis. mytup = () # empty tuple mytup = (3,) # one element mytup = (2, 3, 5, 7) # more elements Why use tuples when we have lists? The immutable property provides integrity. Uses less memory. Better performance. There is more to tuples and lists than this.


Download ppt "Python Lists and Sequences"

Similar presentations


Ads by Google