Python String, List, Tuple, and Dictionary Functions
String Functions
upper(): Converts all characters of a string to uppercase.
Example:
'hello'.upper() => 'HELLO'
lower(): Converts all characters of a string to lowercase.
Example:
'HELLO'.lower() => 'hello'
find(): Returns the index of the first occurrence of a substring. Returns -1 if not found.
Example:
'search'.find('r') => 3
Exception: No exception, just returns -1 if not found.
replace(): Replaces all occurrences of a substring with another substring.
Example:
'replace'.replace('e', 'a') => 'raplaca'
strip(): Removes leading and trailing spaces from a string.
Example:
' hello '.strip() => 'hello'
split(): Splits a string into a list based on a delimiter.
Example:
'one,two,three'.split(',') => ['one', 'two', 'three']
join(): Joins a list of strings into a single string with a specified delimiter.
Example:
','.join(['one', 'two', 'three']) => 'one,two,three'
List Functions
append(): Adds an element to the end of the list.
Example:
[1, 2].append(3) => [1, 2, 3]
extend(): Adds all elements of an iterable to the end of the list.
Example:
[1, 2].extend([3, 4]) => [1, 2, 3, 4]
pop(): Removes and returns the element at the specified index.
Example:
[1, 2, 3].pop(1) => 2 (and list becomes [1, 3])
Exception: Raises IndexError if the list is empty or index is out of range.
remove(): Removes the first occurrence of the specified value.
Example:
[1, 2, 3, 2].remove(2) => [1, 3, 2]
Exception: Raises ValueError if the value is not present.
sort(): Sorts the list in ascending order by default.
Example:
[3, 1, 2].sort() => [1, 2, 3]
reverse(): Reverses the elements of the list.
Example:
[1, 2, 3].reverse() => [3, 2, 1]
Tuple Functions
count(): Returns the number of occurrences of a specified value.
Example:
(1, 2, 2, 3).count(2) => 2
index(): Returns the index of the first occurrence of the specified value.
Example:
(1, 2, 3).index(2) => 1
Exception: Raises ValueError if the value is not present.
Dictionary Functions
get(): Returns the value for the specified key if the key is in the dictionary.
Example:
{'a': 1}.get('a') => 1
Exception: Returns None if the key is not found.
keys(): Returns a view object with all the keys of the dictionary.
Example:
{'a': 1}.keys() => dict_keys(['a'])
values(): Returns a view object with all the values of the dictionary.
Example:
{'a': 1}.values() => dict_values([1])
items(): Returns a view object with a list of key-value pairs.
Example:
{'a': 1}.items() => dict_items([('a', 1)])
pop(): Removes and returns the value for the specified key.
Example:
{'a': 1}.pop('a') => 1
Exception: Raises KeyError if the key is not found.
update(): Updates the dictionary with elements from another dictionary or an iterable of key-value
pairs.
Example:
{'a': 1}.update({'b': 2}) => {'a': 1, 'b': 2}