






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







x.index(5) → 0 x.count(6) → 2 len(x) → 6 x[4] → 15 x[1:3] → [6, 9] x[3:] → [6, 15, 5] x[–2] → 15 x + [1, 2] → [5, 6, 9, 6, 15, 5, 1, 2] x * 2 → [5, 6, 9, 6, 15, 5, 5, 6, 9, 6, 15, 5] 15 in x → True s.index(‘s’) → 0 s.count(‘t’) → 1 len(s) → 6 s[4] → “h” s[1:3] → “li” s[3:] → “thy” s[–2] → “h” s + ‘ toves’ → “slithy toves” s * 2 → “slithyslithy” ‘t’ in s → True the smallest i for which x[i] == 5 the number of i s for which x[i] == 6 methods built-in fn. slicing operators
Does not work for strings s = 'Hello World!' s[0] = 'J' ERROR s.append('?') ERROR See Python Standard Library for more methods
swap(x, 3, 4)
def swap(b, h, k): """Procedure swaps b[h] and b[k] in b Precondition: b is a mutable list, h " and k are valid positions in the list""” temp= b[h] b[h]= b[k] b[k]= temp Swaps b[h] and b[k], because parameter b contains name of list. 1 2 3 b h k temp swap:1 2 3 id7 3 4 id 3 4 0 1 1 2 5 3 9 4 3 5 2 6 0 7 x id ✗ ✗ 9 5 5 ✗ ✗ ✗
id 5 6 0 1 5 2 id 3 x id8 id 6 5 0 1 y id Point x 3. y 4. z 5. id
id 5 6 0 1 5 2 id 3 z id
…a horse and carriage? Bread and butter? text = 'Rama lama lama\nke ding a de ding a dong' words = text.split() lines = text.split('\n') sep = '-' print sep.join(words) s = (sep.join(lines[0].split()) + ' ' + sep.join(lines[1].split())) text.split(sep): return a list of the words in text (separated by sep, or whitespace by default) sep.join(words): concatenate the items in the list of strings words, separated by sep. [‘Rama’, ‘lama’, ‘lama’, ‘ke’, …] returns a list of two strings ‘Rama-lama-lama-ke…’ ‘Rama-lama-lama ke-ding-a-de-ding-a-dong’ docsity.com
§ The map function: map(⟨ function ⟩, ⟨ list ⟩) § The for statement: for ⟨ variable ⟩ in ⟨ list ⟩: ⟨ statements ⟩ Call the function once for each item in the list, with the list item as the argument, and put the return values into a list. Execute the statements once for each item in the list, with the value of the variable set to the list item.