Tutorial by Examples: d

Getting the minimum or maximum or using sorted depends on iterations over the object. In the case of dict, the iteration is only over the keys: adict = {'a': 3, 'b': 5, 'c': 1} min(adict) # Output: 'a' max(adict) # Output: 'c' sorted(adict) # Output: ['a', 'b', 'c'] To keep the dictionary ...
Using one sequence: sorted((7, 2, 1, 5)) # tuple # Output: [1, 2, 5, 7] sorted(['c', 'A', 'b']) # list # Output: ['A', 'b', 'c'] sorted({11, 8, 1}) # set # Output: [1, 8, 11] sorted({'11': 5, '3': 2, '10': 15}) # dict # Output: ['10', '11...
Getting the minimum of a sequence (iterable) is equivalent of accessing the first element of a sorted sequence: min([2, 7, 5]) # Output: 2 sorted([2, 7, 5])[0] # Output: 2 The maximum is a bit more complicated, because sorted keeps order and max returns the first encountered value. In case th...
Instead of this lambda-function that calls the method explicitly: alist = ['wolf', 'sheep', 'duck'] list(filter(lambda x: x.startswith('d'), alist)) # Keep only elements that start with 'd' # Output: ['duck'] one could use a operator-function that does the same: from operator import metho...
What can be documented? Examples of functions for various languages. A brief introduction of each tag. What is the difference between a question and a topic? Topics have a broader scope than questions; documentation topics that are asked as a question can be closed because they are too bro...
Arguments are defined in parentheses after the function name: def divide(dividend, divisor): # The names of the function and its arguments # The arguments are available by name in the body of the function print(dividend / divisor) The function name and its list of arguments are called...
Optional arguments can be defined by assigning (using =) a default value to the argument-name: def make(action='nothing'): return action Calling this function is possible in 3 different ways: make("fun") # Out: fun make(action="sleep") # Out: sleep # The argumen...
One can give a function as many arguments as one wants, the only fixed rules are that each argument name must be unique and that optional arguments must be after the not-optional ones: def func(value1, value2, optionalvalue=10): return '{0} {1} {2}'.format(value1, value2, optionalvalue1) Wh...
Arbitrary number of positional arguments: Defining a function capable of taking an arbitrary number of arguments can be done by prefixing one of the arguments with a * def func(*args): # args will be a tuple containing all values that are passed in for i in args: print(i) fun...
<a href="example.com" target="_blank">Text Here</a> The target attribute specifies where to open the link. By setting it to _blank, you tell the browser to open it in a new tab or window (per user preference). SECURITY VULNERABILITY WARNING! Using target="...
The increment and decrement operators exist in prefix and postfix form. int a = 1; int b = 1; int tmp = 0; tmp = ++a; /* increments a by one, and returns new value; a == 2, tmp == 2 */ tmp = a++; /* increments a by one, but returns old value; a == 3, tmp == 2 */ tmp = --b; ...
min, max, and sorted all need the objects to be orderable. To be properly orderable, the class needs to define all of the 6 methods __lt__, __gt__, __ge__, __le__, __ne__ and __eq__: class IntegerContainer(object): def __init__(self, value): self.value = value def __rep...
class MyClass { func sayHi() { print("Hello") } deinit { print("Goodbye") } } When a closure captures a reference type (a class instance), it holds a strong reference by default: let closure: () -> Void do { let obj = MyClass() // Captures a strong re...
There are several special variable types that a class can use for more easily sharing data. Instance variables, preceded by @. They are useful if you want to use the same variable in different methods. class Person def initialize(name, age) my_age = age # local variable, will be destroyed ...
We have three methods: attr_reader: used to allow reading the variable outside the class. attr_writer: used to allow modifying the variable outside the class. attr_accessor: combines both methods. class Cat attr_reader :age # you can read the age but you can never change it attr_writer...
There is a problem when using optional arguments with a mutable default type (described in Defining a function with optional arguments), which can potentially lead to unexpected behaviour. Explanation This problem arises because a function's default arguments are initialised once, at the point whe...
Python 2.x2.3 raw_input will wait for the user to enter text and then return the result as a string. foo = raw_input("Put a message here that asks the user for input") In the above example foo will store whatever input the user provides. Python 3.x3.0 input will wait for the user ...
Python 2.x2.3 In Python 2.x, to continue a line with print, end the print statement with a comma. It will automatically add a space. print "Hello,", print "World!" # Hello, World! Python 3.x3.0 In Python 3.x, the print function has an optional end parameter that is what...
There are different modes you can open a file with, specified by the mode parameter. These include: 'r' - reading mode. The default. It allows you only to read the file, not to modify it. When using this mode the file must exist. 'w' - writing mode. It will create a new file if it does no...
The simplest way to iterate over a file line-by-line: with open('myfile.txt', 'r') as fp: for line in fp: print(line) readline() allows for more granular control over line-by-line iteration. The example below is equivalent to the one above: with open('myfile.txt', 'r') as fp: ...

Page 17 of 691