Download presentation
Presentation is loading. Please wait.
Published byΤελεσφόρος Παπανδρέου Modified over 6 years ago
1
Basic Python Collective variables (sequences) Lists (arrays)
Strings (lists of characters) Dictionaries (hashes, associative arrays) BoP covers these mostly in Data Structures (p 75) Week 1
2
Basic Python Lists an ordered collection of items
items can be any data type items do not need to all be the same type Create a list bases = [ ‘A’, ‘C’, ‘G’, ‘T’ ] bases = list( ‘A’, ‘C’, ‘G’, ‘T ’) bases = [] bases.append( ‘A’ ) bases.append( ‘C’ ) bases.append( ‘G’ ) bases.append( ‘T’ ) Week 1
3
Basic Python Lists Access to list elements, zero based index bases = [ ‘a’, ‘c’, ‘g’, ‘t’ ] bases[0] is a bases[3] is t bases[4] => IndexError: list index out of range negative index counts from the right print( bases[-1] ) => t print(bases) ['a', 'c', 'g', 't'] bases[0] = ‘c‘ bases[2] = ‘c‘ print( 'bases:', bases ) bases: ['c', 'c', 'c', 't'] bases[4] = ‘c’ NO, IndexError: list assignment index out of range must use bases.append[‘c’] deleting an element print(bases) ['a', 'c', 'g', 't'] del bases[1] print(bases) ['a', 'g', 't'] list.remove(‘c’) Week 1
4
Basic Python Lists useful functions given bases = [ ‘a’, ‘c’, ‘g’, ‘t’ ] how long is the list? len(bases) => 4 Is a known element in the list? bases.index(‘g’) => ‘g’ in bases => True ‘n’ in bases => False concatenating lists extra = ['r', 'y', 'n' ] all = bases + extra print(all) => ['a', 'c', 'g', 't', 'r', 'y', 'n'] duplicating lists double = bases * 2 print(double) => ['a', 'c', 'g', 't', 'a', 'c', 'g', 't'] counting items print( double.count(‘a’) ) => double.remove(‘a’) print( double.count(‘a’) ) => print( double ) => ['c', 'g', 't', 'a', 'c', 'g', 't'] reverse a list bases.reverse() print(bases) print( bases ) => ['t', 'g', 'c', 'a'] Week 1
5
Basic Python Lists Slices – sublist of a list - list[begin:end+1] bases[0:3] => ['a', 'c', 'g'] bases[0:-1] => ['a', 'c', 'g'] bases[3:1] => No, can’t go backwards, [] Copying lists – Doesn’t work like you expect bases = [ ‘a’, ‘c’, ‘g’, ‘t’ ] save = bases bases[1] = ‘a’ print( save ) => ['a', 'a', 'g', 't'] save is not a copy! save = bases[:] bases[1] = ‘a’ print( save ) => ['a', ‘c', 'g', 't'] save is a copy! also save = list( base ) Week 1
6
Basic Python Lists Iterating with lists for <dummy_variable> in <list>: Second kind of loop in python for base in bases: print(‘base:’, base ) i = 0 for base in bases: print( ‘base(‘, i, ‘) =‘, base ) A new way using range for i in range( 0, 4 ): print( ‘base(‘, i, ‘) =‘, bases[i] ) for i in range( 0, len(bases) ): print( ‘base(‘, i, ‘) =‘, bases[i] ) for i in range( len(bases) ): print( ‘base(‘, i, ‘) =‘, bases[i] ) for i in range( 0, len(bases), 2 ): # every other one print( ‘base(‘, i, ‘) =‘, bases[i] ) for i in reversed(range( len(bases) ) ): # count down not up print( ‘base(‘, i, ‘) =‘, bases[i] ) Week 1
7
Basic Python Strings Strings are essentially a list of characters Most features/functions work just like lists bases = ‘acgt’ bases[0] => ‘a’ bases[3] => ‘t’ bases[4] => IndexError: string index out of range bases[1:3] => ‘cg’ bases[-1] => ‘t’ len(bases) => ‘a’ in bases => True ‘A’ in bases => False bases.count( ‘a’ ) => 1 Iteration for strings for b in bases: print(b) for i in range( len(bases) ): print( bases[i] ) Week 1
8
Basic Python Strings List methods that do not work with strings
append ( use +=) reverse del remove Week 1
9
Basic Python Strings There are many specialized methods for strings (must import string) Predefined constants string.ascii_lowercase- lowercase letters 'abcdefghijklmnopqrstuvwxyz'. string.ascii_uppercase - uppercase letters 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. string.ascii_letters - concatenation of the ascii_lowercase and ascii_uppercase string.digits - ' ' string.hexdigits - ' abcdefABCDEF'. string.octdigits - ' '. string.punctuation - String of ASCII characters which are considered punctuation string.whitespace - all ASCII characters that are considered whitespace. includes the characters space, tab, linefeed, return, formfeed, and vertical tab. string.printable - String of ASCII characters which are considered printable combination of digits, ascii_letters, punctuation, and whitespace. Week 1
10
Basic Python Strings Week 1 String methods – tests str.isalnum()
Return true if all characters in the string are alphanumeric and there is at least one character, false otherwise. A character c is alphanumeric if one of the following returns True: c.isalpha(), c.isdecimal(), c.isdigit(), or c.isnumeric(). str.isalpha() Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. str.isdecimal() Return true if all characters in the string are decimal characters and there is at least one character, false otherwise. str.isdigit() Return true if all characters in the string are digits and there is at least one character, false otherwise. str.islower() Return true if all cased characters in the string are lowercase and there is at least one cased character, false otherwise. str.isnumeric() Return true if all characters in the string are numeric characters, and there is at least one character, false otherwise. str.isprintable() Return true if all characters in the string are printable or the string is empty, false otherwise. str.isspace() Return true if there are only whitespace characters in the string and there is at least one character, false otherwise. str.isupper() Return true if all cased characters in the string are uppercase and there is at least one cased character, false otherwise. Week 1
11
Basic Python Strings Complete list of string methods
Most important (IMO) str.count(sub[, start[, end]]) Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. str.strip([chars]) str.lstrip([chars]) str.rstrip([chars]) Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped: str.startswith(prefix[, start[, end]]) str.endswith(suffix[, start[, end]]) Return True if the string starts or ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position. Week 1
12
Basic Python String methods str.join(iterable) str.lower() str.upper()
Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method. str.lower() Return a copy of the string with all the cased characters converted to lowercase. str.upper() Return a copy of the string with all the cased characters converted to uppercase. str.replace(old, new[, count]) Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. str.split(sep=None, maxsplit=-1) Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made). If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns ['']. Week 1
13
Basic Python Dictionaries (hashes, associative arrays)
a list indexed by a string instead of a number base = { ‘a’:adenine, ‘c’:cytosine’, ‘g’:’guanine’, ‘t’:’thymine’ } base = {} base[‘a’] = ‘adenine’ … base = dict() base[‘a’] = ‘adenine’ … Week 1
14
Basic Python Dictionaries
Iterating with dictionaries for k in bases.keys(): print( ‘base(‘, k, ‘ ) =‘, bases[k] ) for v in bases.values(): print( v ) for k,v in bases.items(): print( ‘base(‘, k, ‘ ) =‘, v ) del works with dictionaries (deletes the specified key and its value) Week 1
15
Basic Python Other collective variables
tuple – similar to a constant list, god for permanent definitions bases = ( ‘a’, ‘c’, ‘g’, ‘t’ ) a tuple can be empty a = () if it has only one item, the syntax is special a = (2, ) access values like list Week 1
16
Basic Python Other collective variables
sets – an un ordered collection bri = set(['brazil', 'russia', 'india']) methods add() clear() copy() difference() bri.add('colombia') bri => {'brazil', 'colombia', 'russia', 'india'} sa = set(['colombia', 'brazil']) bri.difference(sa) => {'russia', 'india'} sa.difference(bri) => set() discard() remove() intersection() union() bri = bri.union(sa) bri => {'brazil', 'russia', 'india', 'colombia'} isdisjoint() issubset() issuperset() Week 1
17
Basic Python Week 1
18
Basic Python Week 1
19
Basic Python Week 1
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.