The list elements can be anything and each list element can have a completely different type. This is not allowed in arrays. Arrays are objects with definite type and size
A = [ ] # This is a blank list variableB = [2,4,'john'] # lists can contain different variable types.
Tuple
Similar to list, but immutable like strings i.e. you cannot modify tuples
Tuples are heterogeneous data structures (i.e., their entries have different meanings), while lists are homogeneous sequences.
can be used as the key in Dictionary
tuple is declared in parentheses ( )
tupleA = (1,2,3,4)person=(‘ABC’,’admin’,’12345')# This gives error: 'tuple' cannot be assignedtupleA[2] = 5
Dictionary
A dictionary is a key:value pair, like an address-book. i.e. we associate keys (name) with values (details).
written with curly brackets { }
A colon (:) separates each key from its value.
the key must be unique and immutable (tuples, not list)
# create a dictionary using two liststudents = ['Amanda','Teresa','Paula','Mario']ages = [27,38,17,40]# zip method --> iterator of tuples --> dict method --> dictionarystudents_ages =dict(zip(students, ages))print(students_ages)# {'Amanda': 27, 'Teresa': 38, 'Paula': 17, 'Mario': 40}# create a dictionary with dict() function using keyword arguments# dictionary - ages of studentsstudents_ages =dict(Amanda=27, Teresa=38, Paula=17, Mario=40)print(students_ages)# {'Amanda': 27, 'Teresa': 38, 'Paula': 17, 'Mario': 40} students_ages ={'Amanda':27,'Teresa':38,'Paula':17,'Mario':40}print(students_ages)
Class in Python
Instance methods
Called using objects
Must have self as the first parameter
(self is another python term. We can use self to access any data or other instance methods which resides in that class. These cannot be accessed without using self)
Initializer Method
must be called __init__()~~(~~double underscore is used by python runtime)
The first parameter is self
If the initializer method is present, the constructor calls __init__()
Super() to inherit all the methods and properties from another class:
Inherits all the method, properties of Parent or sibling class
>**_The underscore prefix in a variable/method name is meant as a _hint to another programmer that a variable or method starting with a single underscore is intended only for internal use. This convention is defined in PEP 8.
# Base classclassHouse:''' A place which provides with shelter or accommodation '''def__init__(self,rooms,bathrooms): self.rooms = rooms self.bathrooms = bathroomsdefroom_details(self):print(f'This property has {self.rooms} rooms \ with {self.bathrooms} bathrooms')classApartment(House):''' A house within a large building where others also have their own house '''def__init__(self,rooms,bathrooms,floor): House.__init__(self, rooms, bathrooms) self.floor = floor# Create an Apartmentapartment =Apartment(2, 2, 21)apartment.room_details()Output:This property has 2 rooms with2 bathrooms
Index of array
.shape
input_tensor.shape[-1] # get value of the last index of shape
"""
Google Style
Args:
param1: This is the first param.
param2: This is a second param.
Returns:
This is a description of what is returned.
Raises:
KeyError: Raises an exception.
"""
Names to Avoid
dashes (-) in any package/module name
Use CapWords for class names, but lower_with_under.py for module names.
Guidelines for naming
Example Google style docstrings
This module demonstrates documentation as specified by the Google Python Style Guide
"""A one line summary of the module or program, terminated by a period.Leave one blank line. The rest of this docstring should contain anoverall description of the module or program. Optionally, it may alsocontain a brief description of exported classes and functions and/or usageexamplesExample: Examples can be given using either the ``Example`` or ``Examples`` sections. Sections support any reStructuredText formatting, including literal blocks:: $ python example_google.pySection breaks are created by resuming unindented text. Section breaksare also implicitly created anytime a new section starts.Attributes: module_level_variable1 (int): Module level variables may be documented in either the ``Attributes`` section of the module docstring, or in an inline docstring immediately following the variable. Either form is acceptable, but the two should not be mixed. Choose one convention to document module level variables and be consistent with it.Todo: * For module TODOs * You have to also use ``sphinx.ext.todo`` extension.. _Google Python Style Guide: https://google.github.io/styleguide/pyguide.html"""deffunction_with_types_in_docstring(param1,param2):"""Example function with types documented in the docstring. `PEP 484`_ type annotations are supported. If attribute, parameter, and return types are annotated according to `PEP 484`_, they do not need to be included in the docstring: Args: param1 (int): The first parameter. param2 (str): The second parameter. Returns: bool: The return value. True for success, False otherwise. .. _PEP 484: https://www.python.org/dev/peps/pep-0484/ """defmodule_level_function(param1,param2=None,*args,**kwargs):"""This is an example of a module level function. Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and description of each parameter is optional, but should be included if not obvious. If ``*args`` or ``**kwargs`` are accepted, they should be listed as ``*args`` and ``**kwargs``. The format for a parameter is:: name (type): description The description may span multiple lines. Following lines should be indented. The "(type)" is optional. Multiple paragraphs are supported in parameter descriptions. Args: param1 (int): The first parameter. param2 (:obj:`str`, optional): The second parameter. Defaults to None. Second line of description should be indented. *args: Variable length argument list. **kwargs: Arbitrary keyword arguments. Returns: bool: True if successful, False otherwise. The ``Returns`` section supports any reStructuredText formatting, including literal blocks:: { 'param1': param1, 'param2': param2 } Raises: AttributeError: The ``Raises`` section is a list of all exceptions that are relevant to the interface. ValueError: If `param2` is equal to `param1`. """if param1 == param2:raiseValueError('param1 may not be equal to param2')returnTrue