Tutorial by Examples

String also have an index method but also more advanced options and the additional str.find. For both of these there is a complementary reversed method. astring = 'Hello on StackOverflow' astring.index('o') # 4 astring.rindex('o') # 20 astring.find('o') # 4 astring.rfind('o') # 20 The ...
All built-in collections in Python implement a way to check element membership using in. List alist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 5 in alist # True 10 in alist # False Tuple atuple = ('0', '1', '2', '3', '4') 4 in atuple # False '4' in atuple # True String astring = 'i am a s...
list and tuple have an index-method to get the position of the element: alist = [10, 16, 26, 5, 2, 19, 105, 26] # search for 16 in the list alist.index(16) # 1 alist[1] # 16 alist.index(15) ValueError: 15 is not in list But only returns the position of the first found element: ...
dict have no builtin method for searching a value or key because dictionaries are unordered. You can create a function that gets the key (or keys) for a specified value: def getKeysForValue(dictionary, value): foundkeys = [] for keys in dictionary: if dictionary[key] == value: ...
Sorted sequences allow the use of faster searching algorithms: bisect.bisect_left()1: import bisect def index_sorted(sorted_seq, value): """Locate the leftmost value exactly equal to x or raise a ValueError""" i = bisect.bisect_left(sorted_seq, value) ...
Searching in nested sequences like a list of tuple requires an approach like searching the keys for values in dict but needs customized functions. The index of the outermost sequence if the value was found in the sequence: def outer_index(nested_sequence, value): return next(index for index, ...
To allow the use of in for custom classes the class must either provide the magic method __contains__ or, failing that, an __iter__-method. Suppose you have a class containing a list of lists: class ListList: def __init__(self, value): self.value = value # Create a set of al...

Page 1 of 1