Python Basics
Python Basics
How to input multiple values from users in one line
x,y = input(), input()
## or
a,b = input().split()
print(a)
print(b)
10 20
30 40
a b
a
b
How to typecast built-in function input( )
input( ) function returns a string, so users can typecase to an int or a float.
Python Operators
- Arithmetic Operators
- Arithmetic Operators differ from those of Java in that divison “/” divides into a float and “//” divides with respect to floor rule (similar to that of division in Java.)
- Comparison Operators
- ”>=, <=” : the order matters for these greater than or less than signs
- Logical Operators
- Compared to Java operators, Python uses the words “and”, “or”, and “not” for denoting logical operators
- Identity Operator
- “is” and “is not” are the identity operators both used to check if tow values are located on the same part of the memory
- Membership Operators
- “in” and “not in” are the membership operators both used to test whether a value or variable is in a sequence
- Sequence in Python are list, tuple, and range
Writing ternary in Python
## Java
## int a = 20 > 10? 1 : 0;
## Python
a = 1 if 20 > 10 else 0
- How is “==” and “is” operator different in Python
”==” is a comparison operator that compares values, whereas the “is” operator is the identity operator that checks whehter the operands refer to the same object or not (same memory location.)
Data Types in Python
- Strings
- immutable
- String.endswith() –> returns true if a string ends with the given suffix otherwise, returns False
- String.startswith()
- str.format()
- str.count
- str.strip()
- Lists
- uses “[ ]”
- mutable –> dynamically sized arrays (similar to ArrayList)
- does not need to be homogeneous
- may contain duplicate values with their distinct positions
- used for implementing stacks and queues
- append() –> adds one element to the list
- insert(‘position’, ‘value’) –> adds element at specified index
- extend() –> adds multiple elements at the end of the list
- reverse()
- remove() –> removes a specific element in the list
- pop() –> removes and returns the last element of the list
- len() –> returns the size of the list
- map(‘function’, ‘iter’) –> returns a list of the results after applying the given function to each item of a given iterable
- lambda() –> this function can have any number of arguments but only one expression, which is evaluated and returned
- Tuples
- uses “( )”
- sequenece of immutable Python objects
- a little bit faster than lists
- similar to Lists, does not need to be homogeneous
- complexities for creating tuples: O(1)
- complexities for accessing tuples: O(1)
- concatenation of tuples is done by ‘+’ operator, but it can be only done with homogenous tuples
- sorted(‘iterable’, ‘key’ for comparison) –> input elements in the tuple and return a new sorted list
- we generally use ‘tuples’ for heterogeneous data types and ‘lists’ for homogenous data types
- Sets
- unordered collection of data types that is iterable, mutable, and has no duplicate elements
- uses “{ }”
- set cannot have mutable elements like a list or dictionary, as it is mutable
- sets can have tuple as an element since tuples are immutable objects
- add() –> adds an element to a set –> O(1) operation
- remove(), discard() –> removes an element from a set
- pop() –> removes and returns an arbitrary set element
- union(), difference(), intersection(), isdisjoint(), issubset() –> set operators
- Dictionary
- unordered collection of data values, used to store data values like map, which holds key:value pair
- uses “{Key : value}”
- values in a dictionary can be of any data type and can be duplicated, whereas keys can’t be repeated and must be immutable
- therefore, lists cannot be keys, whereas they can be used as values
- complexities for creating a dictionary: O(len(dict))
- complexities for adding elements in a dictionary: O(1)/O(n)
- complexities for accessing elements in a dictionary: O(1)
- get() –> returns the value of specified key
- items() –> returns a list containing a tuple for each key value pair
- keys() –> returns a list containing dictionary’s keys
- pop() –> removes the element with specified key
- popitem() –> removes the last inserted key-value pair
- update() –> updates dictionary with specified key-value pairs
- values() –> returns a list of all the values of dictionary
- Arrays
- collection of items of the same type stored at contiguous memeory locations
- array can be created by importing array module –> import array
- array(‘data type’, ‘value_list’)
- compelxities for creating of arrays: O(1)
- complexities for adding elements to arrays: O(1)/O(n) for inserting at the end, O(n) for inserting at the beginning
- complexities for searching elements in arrays: O(n)
- pop() or remove() used to remove elements
- insert() or append() used to add elements
How to use comparison operator Chaining
”>” | ”<” | ”==” | ”>=” | ”<=” | ”!=” | “is” [“not”] | [“not”] “in” all have same interpretation that is conventional in mathematics. |
How to use while loop with list
# checks if list still contains any element
a = [1, 2, 3, 4]
while a:
print(a.pop())
4
3
2
1
How to use while loop in a single line
can seperate lines with a semicolon
count = 0
while(count < 5): count += 1; print("Count!")
Count!
Count!
Count!
Count!
Count!
Different looping techniques using Python data structures
## using enumerate() to loop through the interable
## in order to print index number along with the value
for key, value in enumerate(['The', 'Big', 'Bang', 'Theory']):
print(key, value)
0 The
1 Big
2 Bang
3 Theory
## using items() to loop through dictionary printing
## key-value pair sequentially
king = {'Akbar': 'The Great', 'Chandragupta': 'The Maurya',
'Modi': 'The Changer'}
for key, value in king.items():
print(key, value)
Akbar The Great
Chandragupta The Maurya
Modi The Changer
## using sorted() to print ordered list
## can be combined with set() to remove duplicates
lis = [1, 3, 5, 6, 2, 1, 3]
print("The list in sorted order is : ")
for i in sorted(lis):
print(i, end=" ")
print("\r")
print("The list in sorted order (without duplicates) is : ")
for i in sorted(set(lis)):
print(i, end=" ")
The list in sorted order is :
1 1 2 3 3 5 6
The list in sorted order (without duplicates) is :
1 2 3 5 6
Syntax of Python Functions
def function_name(parameters):
Or
def function_name(parameter: data_type) -> return_type:
## example specifying the data and return type
def add(num1: int, num2: int) -> int:
"""Add two numbers"""
num3 = num1 + num2
return num3
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")
The addition of 5 and 15 results 20.
Types of Arguments
- Default Arguments : a parameter that assumes a default value if a value is not provided in the function call for that argument
- once there is a default argument, all the arguments to its right must also have default values
- Keyword Arguments: Python allows functions to be called using keyword arguments. When we call functions in this way, the order (position) of the arguments can be changed.
- keyword arguments should follow positional arguments
- Docstring: first string after the function which describes the functionality of the function
- implemented with “”” right after the function
- print(‘function_name’.doc)
Difference between *args and **kwargs
The special syntax *args in function definitions in Python is used to pass a non-key worded, variable-length argument list. *args allows to take in any number of arguments compared to the number of formal arguments that users previously defined (including zero extra arguments).
The special syntax **kwargs in function definitions in Python allows users to pass through any number of keyword arguments. One can think of kwargs as being a dictionary that maps each keyword to the value that we pass alongside it.
## using *args
def myFun(arg1, *argv):
print ("First argument :", arg1)
for arg in argv:
print("Next argument through *argv :", arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
First argument : Hello
Next argument through *argv : Welcome
Next argument through *argv : to
Next argument through *argv : GeeksforGeeks
def myFun1(*args,**kwargs):
print("args: ", args)
print("kwargs: ", kwargs)
myFun1('geeks','for','geeks',first="Geeks",mid="for",last="Geeks")
args: ('geeks', 'for', 'geeks')
kwargs: {'first': 'Geeks', 'mid': 'for', 'last': 'Geeks'}
What is Generator Expression in Python?
Generator expressions are comparable to list comprehensions, both being another way to generate sequence types such as arrays, tuples, and collections within Python.
Generator expressions are memory-efficient in comparison to list comprehensions, with the use of ‘yield’ rather than returning the items within the iterator.
Generator expressions are also more time-efficient compared to list comprehensions.
What is Lambda keyword in Python?
Syntax:
lambda arguments: expression
Lambda keywords are used to create anonymous functions. These functions can have any number of arguments but only one expression, which is evaluate and returned.
We can replace list comprehension with lambda by using map() or filter() methods.
a = [100, 2, 8, 60, 5, 4, 3, 31, 10, 11]
# in filter either we use assignment or conditional operator,
# the pass actual parameter will get return
filtered = filter (lambda x: x % 2 == 0, a)
print(list(filtered))
# in map either we use assignment or conditional operator,
# the result of the value will get returned
mapped = map (lambda x: x % 2 == 0, a)
print(list(mapped))
[100, 2, 8, 60, 4, 10]
[True, True, True, True, False, True, False, False, True, False]