myList = ["a string", 1.234, True]
>>> len( myList ) 3
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> options = ["Create", "Read", "Update", "Delete"] >>> options[2] 'Update' >>> options[1] = "Select" >>> options ['Create', 'Select', 'Update', 'Delete']
i = 0 while i < 10: print(i) i = i + 1
options = ["Create", "Read", "Update", "Delete"] i = 0 while i < len(options): print( options[i] ) i = i + 1
>>> items = [0, 1, 2, 3, 4, 5] >>> del items[2] >>> items [0, 1, 3, 4, 5]
>>> ["a", "b", "c"] + ["d", "e"] ['a', 'b', 'c', 'd', 'e']
>>> items = [0, 1, 2, 3, 4, 5] >>> items[1:3] # elements from index 1 to 3, [1, 2] # including 1, excluding 3 >>> items[:3] # elements up to but excluding 3 [0, 1, 2] >>> items[1:] # elements from index 1 to end [1, 2, 3, 4, 5]
>>> items = [0, 1, 2, 3, 4, 5] >>> items[-1] # Get the last element on the list 5 >>> items[-2] # Second-to-last element on the list 4 >>> items[-3:] # Third-to-last to the end [3, 4, 5]
Access many list manipulation functions using dot-notation (just like modules)
L.append(x) | - add an item to the end of L |
L.extend(M) | - append all items in M to the end of L |
L.insert(i, x) | - insert x into L at position i |
L.remove(x) | - remove the first occurance of x from L |
L.pop(i) | - remove the item at position i and return it (or from end if no i) |
L.index(x) | - find the index of the first item that matches x on L |
L.count(x) | - return the number of times x occurs in L |
L.sort() | - sort the items in L, in place |
L.reverse() | - reverse the order of items in L, in place. |
>>> s = 'abcdefg' >>> len(s) 6 >>> s[0] 'a' >>> s[1] 'b' >>> s[:3] 'abc' >>> s[-3:] 'def'
>>> consts = ('CENTER', 'CORNER', 'OTHER')
>>> consts[1]
'CORNER'
>>> consts[1:]
('CORNER', 'OTHER')
>>> del consts[0]
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion
Use the for-in statement to loop over all elements of a sequence type (list, string, ...)
for variable in list : statement1 statement2
>>> for op in ['tall', 'grande', 'venti']: >>> print( op + ' is an option' ) tall is an option grande is an option venti is an option
The built-in range() function helps us with for-in statements
range(min, max) | - generates a list of numbers from min to max-1 |
range(max) | - generates a list of numbers from 0 to max-1 |
range(min, max, skip) | - generates a list of every skip number from min to max-1 |
>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(4, 10) [4, 5, 6, 7, 8, 9] >>> range(4, 10, 2) [4, 6, 8]
The built-in range() function helps us with for-in statements
sizes = ['tall', 'grande', 'venti'] for i in range( len(sizes) ): print( i, sizes[i] ) 0 tall 1 grande 2 venti
/
#