Tutorial by Examples

For any iterable (for eg. a string, list, etc), Python allows you to slice and return a substring or sublist of its data. Format for slicing: iterable_name[start:stop:step] where, start is the first index of the slice. Defaults to 0 (the index of the first element) stop one past the last in...
A quick way to make a copy of an array (as opposed to assigning a variable with another reference to the original array) is: arr[:] Let's examine the syntax. [:] means that start, end, and slice are all omitted. They default to 0, len(arr), and 1, respectively, meaning that subarray that we are ...
You can use slices to very easily reverse a str, list, or tuple (or basically any collection object that implements slicing with the step parameter). Here is an example of reversing a string, although this applies equally to the other types listed above: s = 'reverse me!' s[::-1] # '!em esrever...
class MultiIndexingList: def __init__(self, value): self.value = value def __repr__(self): return repr(self.value) def __getitem__(self, item): if isinstance(item, (int, slice)): return self.__class__(self.value[item]) r...
Another neat feature using slices is slice assignment. Python allows you to assign new slices to replace old slices of a list in a single operation. This means that if you have a list, you can replace multiple members in a single assignment: lst = [1, 2, 3] lst[1:3] = [4, 5] print(lst) # Out: [1...
Slices are objects in themselves and can be stored in variables with the built-in slice() function. Slice variables can be used to make your code more readable and to promote reuse. >>> programmer_1 = [ 1956, 'Guido', 'van Rossum', 'Python', 'Netherlands'] >>> programmer_2 = [ 18...
Python lists are 0-based i.e. the first element in the list can be accessed by the index 0 arr = ['a', 'b', 'c', 'd'] print(arr[0]) >> 'a' You can access the second element in the list by index 1, third element by index 2 and so on: print(arr[1]) >> 'b' print(arr[2]) >> '...

Page 1 of 1