Sunday 3 September 2017

Python Q & A

We can use the type() function to know which class a variable or a value belongs to and isinstance() function to check if it belongs to a particular class.
a = 5

# Output:
print(type(a))
# Output:
print(type(5.0))
# Output: True
print(isinstance(c, complex))
Number system prefix for Python numbers
Number SystemPrefix
Binary'0b' or '0B'
Octal'0o' or '0O'
Hexadecimal'0x' or '0X'
# Output: 107
print(0b1101011)
# Output: 253 (251 + 2)
print(0xFB + 0b10)
# Output: 13
print(0o15)

Python List Methods
append() - Add an element to the end of the list
extend() - Add all elements of a list to the another list
insert() - Insert an item at the defined index
remove() - Removes an item from the list
pop() - Removes and returns an element at the given index
clear() - Removes all items from the list
index() - Returns the index of the first matched item
count() - Returns the count of number of items passed as an argument
sort() - Sort items in a list in ascending order
reverse() - Reverse the order of items in the list
copy() - Returns a shallow copy of the list

Tuple
we cannot change the elements in a tuple. That also means we cannot delete or remove items from a tuple.
But deleting a tuple entirely is possible using the keyword del.
Python Tuple Method
MethodDescription
count(x)Return the number of items that is equal to x
index(x)Return index of first item that is equal to x

Strings:
 Strings are immutable. This means that elements of a string cannot be changed once it has been assigned. We can simply reassign different strings to the same name.
We cannot delete or remove characters from a string. But deleting the string entirely is possible using the keyword del.
The format() method that is available with the string object is very versatile and powerful in formatting strings.
# default(implicit) order
default_order = "{}, {} and {}".format('John','Bill','Sean')
print('\n--- Default Order ---')
print(default_order) #John, Bill and Sean

# order using positional argument
positional_order = "{1}, {0} and {2}".format('John','Bill','Sean')
print('\n--- Positional Order ---')
print(positional_order)#Bill, John and Sean

# order using keyword argument
keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean')
print('\n--- Keyword Order ---')
print(keyword_order)
#Sean, Bill and John
Some of the commonly used methods are lower(), upper(), join(), split(), find(), replace() etc
>>> "PrOgRaMiZ".lower()
'programiz'
>>> "PrOgRaMiZ".upper()
'PROGRAMIZ'
>>> "This will split all words into a list".split()
['This', 'will', 'split', 'all', 'words', 'into', 'a', 'list']
>>> ' '.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string'])
'This will join all words into a string'
>>> 'Happy New Year'.find('ew')
7
>>> 'Happy New Year'.replace('Happy','Brilliant')
'Brilliant New Year
Buit in Functions

enumerate()
Return an enumerate object. It contains the index and value of all the items of set as a pair.
len()Return the length (the number of items) in the set.
max()Return the largest item in the set.
min()Return the smallest item in the set.
sorted()Return a new sorted list from elements in the set(does not sort the set itself).
sum()Retrun the sum of all elements in the set.
Some of the commonly used built ones are enumerate() and len(). 
str = 'cold'

# enumerate()
list_enumerate = list(enumerate(str))
#[(0, 'c'), (1, 'o'), (2, 'l'), (3, 'd')] 
print('list(enumerate(str) = ', list_enumerate)

#character count
print('len(str) = ', len(str)) #4
set
A set is created by placing all the items (elements) inside curly braces {}, separated by comma or by using the built-in function set().
# set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}

# initialize a with {}
a = {}

# check data type of a
# Output:
print(type(a))

# initialize a with set()
a = set()


# check data type of a
# Output:
print(type(a))

Python Set Methods
MethodDescription
add()Add an element to a set
clear()Remove all elements form a set
copy()Return a shallow copy of a set
difference()Return the difference of two or more sets as a new set
difference_update()Remove all elements of another set from this set
discard()Remove an element from set if it is a member. (Do nothing if the element is not in set)
intersection()Return the intersection of two sets as a new set
intersection_update()Update the set with the intersection of itself and another
isdisjoint()Return True if two sets have a null intersection
issubset()Return True if another set contains this set
issuperset()Return True if this set contains another set
pop()Remove and return an arbitary set element. Raise KeyError if the set is empty
remove()Remove an element from a set. If the element is not a member, raise a KeyError
symmetric_difference()Return the symmetric difference of two sets as a new set
symmetric_difference_update()Update a set with the symmetric difference of itself and another
union()Return the union of sets in a new set
update()Update a set with the union of itself and others

 

No comments:

Post a Comment