Oracle Interval Partitioning

In this blog Oracle Range Partition we have explored how we can create range partition in oracle using date as partition key. Also we have seen one example where the range partition key is defined maximum upto ’01-APR-2019′ (Non-inclusive). But we are trying to insert ’20-OCT-2019′ date data, which is not getting mapped to any partition, that’s why ORA-14400 error occurred. See below error report provided by oracle.

SQL Error: ORA-14400: inserted partition key does not map to any partition
14400. 00000 – “inserted partition key does not map to any partition”

Here comes the Interval Partition, which is extension of  Oracle Range Partition in which, interval partitions are automatically created by the database when data is inserted into the partition.

Monthly Partition:

CREATE TABLE T_ACCOUNT
  (
    V_ACCOUNT_NUM  VARCHAR2(100 CHAR),
    V_ACCOUNT_NAME VARCHAR2(200 CHAR),
    ACC_DATE DATE
  )
  PARTITION BY RANGE
  (
    ACC_DATE
  )
  INTERVAL
  (
    NUMTOYMINTERVAL(1, 'MONTH')
  )
  (
    PARTITION P_DEC2018 VALUES LESS THAN (TO_DATE('01-JAN-2019','DD-MON-YYYY'))
  );

After that we have inserted the data of future months, i.e. SEP & OCT for which Partitions were not available. See below insert statements.

INSERT INTO "SAIL_IN_DEV"."T_ACCOUNT" (V_ACCOUNT_NUM, V_ACCOUNT_NAME, ACC_DATE) VALUES ('1234567890', 'ABC', TO_DATE('20-SEP-19', 'DD-MON-RR'));
INSERT INTO "SAIL_IN_DEV"."T_ACCOUNT" (V_ACCOUNT_NUM, V_ACCOUNT_NAME, ACC_DATE) VALUES ('1234567891', 'ABC', TO_DATE('20-OCT-19', 'DD-MON-RR'));
COMMIT;

After committing the data let see the automatic partitions created by Oracle :

2

Notice that a system generated partition named SYS_P601 & SYS_P402 has been created after inserting rows with a partition key greater than the provided partition.

Fetching the data from particular partition : In below example you will able to see only match partition data.

SELECT * FROM T_ACCOUNT partition (SYS_P601);

It would be really painful to look up the system generated partition name every time, if you have to query directly partition. Therefore, oracle provided a syntax to specify a partition is by using the partition for (DATE) clause in the query: See below example:

partition for (to_date(’15-OCT-2019′,’DD-MON-YYYY’));

SELECT * FROM T_ACCOUNT partition  for (to_date('01-SEP-2019','DD-MON-YYYY'));

The following restrictions apply on Interval Partition:

  • Only one partitioning key column allowed (NUMBER or DATE)
  • Minimum one partition must be defined when the table is created.
  • MAXVALUE partition cannot be defined.
  • NULL values are not allowed in the partition column.
  • Can’t be used at the subpartition level.
  • Not supported for index-organized tables.
  • You cannot create a domain index on an interval partitioned table.

 

Daily Partitions Example:

CREATE TABLE T_TRANSACTIONS
  (
    TRANSACTION_KEY NUMBER,
    AMOUNT          NUMBER,
    CUST_ID         NUMBER,
    TRANSACTION_DATE DATE
  )
  PARTITION BY RANGE
  (
    TRANSACTION_DATE
  )
  INTERVAL
  (
    NUMTODSINTERVAL(1, 'day')
  )
  (
    PARTITION P_01012019 VALUES LESS THAN (TO_DATE('01-JAN-2019','DD-MON-YYYY'))
  );

 


Thanks!

Happy Learning! Your feedback would be appreciated!

Oracle Range Partition

Range partitioning is useful when data has some sort of logical range. Example dates or numbers. See below example where monthly range partitions created based on date column in account table.

CREATE TABLE T_ACCOUNT
  (
    V_ACCOUNT_NUM  VARCHAR2(100 CHAR),
    V_ACCOUNT_NAME VARCHAR2(200 CHAR),
    ACC_DATE DATE
  )
  PARTITION BY RANGE
  (
    ACC_DATE
  )
  (
    PARTITION P_DEC2018 VALUES LESS THAN (TO_DATE('01-JAN-2019','DD-MON-YYYY')),
    PARTITION P_JAN2019 VALUES LESS THAN (TO_DATE('01-FEB-2019','DD-MON-YYYY')),
    PARTITION P_FEB2019 VALUES LESS THAN (TO_DATE('01-MAR-2019','DD-MON-YYYY')),
    PARTITION P_MAR2019 VALUES LESS THAN (TO_DATE('01-APR-2019','DD-MON-YYYY'))
  );

 

Fetching the data from particular partition : In below example you will able to see only match partition data.

SELECT * FROM T_ACCOUNT PARTITION(P_MAR2019);

 

Check partitions metadata in user_tab_partitions & subpartitions.

SELECT * FROM USER_TAB_PARTITIONS WHERE TABLE_NAME='T_ACCOUNT';

1

To check the Partition KEY of the table, use below query:

SELECT partition_name,
  column_name,
  high_value,
  partition_position
FROM USER_TAB_PARTITIONS PART ,
  USER_PART_KEY_COLUMNS PART_KEY
WHERE table_name ='T_ACCOUNT'
AND PART.table_name = PART_KEY.name;

In the above example any record having acc_date less than ’01-JAN-2019′ will go to P_DEC2018 partition. See below example:

INSERT
INTO "T_ACCOUNT"
  (
    V_ACCOUNT_NUM,
    V_ACCOUNT_NAME,
    ACC_DATE
  )
  VALUES
  (
    '1234567890',
    'ABC',
    TO_DATE('20-OCT-2010', 'DD-MON-YYYY')
  );
COMMIT;
SELECT * FROM T_ACCOUNT PARTITION (P_DEC2018) ;

In the this example any record having acc_date greater than ’31-MAR-2019′ will error out, as no partition exists for that date.

Example:

INSERT
INTO "T_ACCOUNT"
  (
    V_ACCOUNT_NUM,
    V_ACCOUNT_NAME,
    ACC_DATE
  )
  VALUES
  (
    '1234567890',
    'ABC',
    TO_DATE('20-OCT-2019', 'DD-MON-YYYY')
  );

Error report:
SQL Error: ORA-14400: inserted partition key does not map to any partition
14400. 00000 – “inserted partition key does not map to any partition”
*Cause: An attempt was made to insert a record into, a Range or Composite
Range object, with a concatenated partition key that is beyond
the concatenated partition bound list of the last partition -OR-
An attempt was made to insert a record into a List object with
a partition key that did not match the literal values specified
for any of the partitions.
*Action: Do not insert the key. Or, add a partition capable of accepting
the key, Or add values matching the key to a partition specification

1

Here in this example we can see the partition key is defined maximum upto 2019-04-01 (Non-inclusive) . But we are trying to insert 20-OCT-2019, which is not getting mapped to any partition, that’s why this error occured as date value which we are trying to insert is T_ACCOUNT not satisfying the partition key range criteria.

Solution: To fix it, you may have to add new partitions or add a Maxvalue partition.

ALTER TABLE T_ACCOUNT ADD partition P_OCT2019 VALUES less than (TO_DATE('01-NOV-2019', 'DD-MON-YYYY'));
ALTER TABLE T_ACCOUNT ADD partition P_MAXVALUE VALUES less than (MAXVALUE);

You can also go with : Oracle Interval Partitioning to resolve this issue, but this not preferable.

Drop Partition:

Once historical data is no longer required for business analysis, after retention period the whole partition can be dropped.

DROP PARTITION P_DEC2018;

Updating Key:

When you are trying to update the partition key column for any record.

UPDATE T_ACCOUNT SET ACC_DATE='20-JAN-2019' WHERE v_account_num='1234567890';

Error report:
SQL Error: ORA-14402: updating partition key column would cause a partition change
14402. 00000 – “updating partition key column would cause a partition change”
*Cause: An UPDATE statement attempted to change the value of a partition
key column causing migration of the row to another partition
*Action: Do not attempt to update a partition key column or make sure that
the new partition key is within the range containing the old
partition key.

You can’t move a row with an update: Row movement disabled, which is the default option.

Solution:  We can enable Row movement to partition table T_ACCOUNT. It allows rows to be moved across partitions.

ALTER TABLE T_ACCOUNT ENABLE ROW MOVEMENT;
UPDATE T_ACCOUNT SET ACC_DATE='20-JAN-2019' WHERE v_account_num='1234567890';
COMMIT;

 


Thanks!

Happy Learning! Your feedback would be appreciated!

Python [Post 07] | Tuple

A tuple is a collection which is ordered and unchangeable. It is similar to list, but a tuple is immutable unlike lists which are mutable.

It is created by placing items inside a parentheses (), separated by comma. Parentheses is optional.

# Creating Tuple

empty_tuple = ()
my_tup1 = 'N','S','E','W'
my_tup2 = ('North','South','East','West')

print(type(empty_tuple))
print(my_tup1)
print(my_tup2)

<class ‘tuple’>
(‘N’, ‘S’, ‘E’, ‘W’)
(‘North’, ‘South’, ‘East’, ‘West’)

Other way to create tuple by using the tuple() constructor. See below example.

my_tup3 = tuple((1,'South',5.5,('A','B','C'),[0,1,2]))

print(my_tup3)
print(type(my_tup3))

(1, ‘South’, 5.5, (‘A’, ‘B’, ‘C’), [0, 1, 2])
<class ‘tuple’>

# Creating a tuple having single value

my_tup4 = (4)
print(type(my_tup4)) # But the result is showing int, i.e. this is not a tuple

<class ‘int’>

To create a tuple having single value, Just include comma at last.

my_tup4 = (4,)
print(type(my_tup4)) # Now its a tuple

<class ‘tuple’>

Some Built-in Python Functions

my_tup5 = 1,2.5,3,4

print(type(my_tup5)) # Type
print(len(my_tup5)) # len Function - Gives the total length of the tuple.
print(max(my_tup5)) # max Function - Returns element from the tuple with maximum value.
print(min(my_tup5)) # min Function - Returns element from the tuple with minimum value.

<class ‘tuple’>
4
4
1

### Accessing Tuple Values – Indexing & Slicing

Use the index operator [] to access an item in a tuple. We can use a : to perform slicing which extracts chunk of more than one element as per input. In slicing last index is not included.

sides = 'East','West','North','South'
# Fetch the first element of list sides

print(sides[0])

East

# Fetch the last element of list sides

print(sides[-1])

South

# fetch elements start from index 1st till last

print(sides[1:])

(‘West’, ‘North’, ‘South’)

# fetch elements upto 2nd index, but 2nd is not included

print(sides [:2])

(‘East’, ‘West’)

# fetch element from 1st index to 3rd index

print(sides [1:3])

(‘West’, ‘North’)

# fetching values in case of nested tuple

my_tup = tuple((1,'South',5.5,('A','B','C'),[0,1,2]))

print(my_tup[3][0])
print(my_tup[3][2])

A
C

### Updating Tuples

Python Tuple is immutable i.e. the elements inside a tuple cannot be changed!

sides = ('East','West','North','South')

# Let's try to change the elements of lists sides

sides[0]= 1

TypeError Traceback (most recent call last)
<ipython-input-14-b1dd30231e62> in <module>()
3 # Let’s try to change the elements of lists sides
4
—-> 5 sides[0]= 1
TypeError: ‘tuple’ object does not support item assignment

### Deleting Tuples

Individual element in tuple cannot be removed. Entire tuple can be removed by using del statement.

# Removing tuple completely

del sides
sides # This will raise exception, as sides tuple removed

NameError Traceback (most recent call last)
<ipython-input-16-7623a01b7793> in <module>()
—-> 1 sides # This will raise exception, as sides tuple removed
NameError: name ‘sides’ is not defined

### Concatenation & Repetition of Tuples

sides = ('East','West','North','South')
modesides = ('North-East','North-East','South-East','South-West')

print(sides)
print(modesides)

(‘East’, ‘West’, ‘North’, ‘South’)
(‘North-East’, ‘North-East’, ‘South-East’, ‘South-West’)

# Concatenation

sides = sides + modesides
print(sides)

(‘East’, ‘West’, ‘North’, ‘South’, ‘North-East’, ‘North-East’, ‘South-East’, ‘South-West’)

# Repetition

sides = sides * 2
print(sides)

(‘East’, ‘West’, ‘North’, ‘South’, ‘North-East’, ‘North-East’, ‘South-East’, ‘South-West’, ‘East’, ‘West’, ‘North’, ‘South’, ‘North-East’, ‘North-East’, ‘South-East’, ‘South-West’)

### Tuple Method

Python includes following tuple methods.

Index() :

Returns the index of the first matched item.

sides = 'EAST','West','North','East','South','East'

print(sides.index('East'))
print(sides.index('West'))

3
1

Count():

Returns the count of number of items passed as an argument.

print(sides.count('East'))

2


Thanks!

Happy Learning! Your feedback would be appreciated!

shobhitsingh.in
Github Code Link

Python [Post 06] | Dictionary

Python dictionary is an un-ordered collection of items. It consists of a key value pairs.

  • Python dictionary is un-ordered & cannot be sorted.
  • Value can be almost any Python object.
  • Value can be accessed by unique key in the dictionary.
  • Keys must be of an immutable data type. Example – strings, numbers or tuples.

Creating a dictionary is as simple as placing items inside curly braces {} separated by comma. An item has a key and the corresponding value expressed as a pair, key: value.

{‘key1′:’value1′,’key2′:’value2’}

# Examples of Python Dictionary:

# Dictionary having string keys & string value
my_dict0 = { "N": "North", "S": "South", "E": "East", "W": "West" }

# Dictionary having integer keys & string value
my_dict1 = { 1: 'North', 2: 'South', 3: 'East', 4: 'West'}

# Dictionary having string keys & integer value
my_dict2 = { 'North' : 1, 'South': 2, 'East': 3,'West':4}

# Dictionary having mixed keys & values
my_dict3 = { 'N' : 'North', 2: 'South', 'East': 3,'West':'W', "ComplexNumber":5+500j, 5.5:[1,2,3,4]}

# Nested Dictionary
my_dict4 = { 'Aphabets' : { 'A':{'Fruit':'Apple','Object':'Aeroplane'},'B':{'Fruit':'Banana','Object':'Ball'}} ,
'Numbers' : { 0: 'Zero', 1:'One', 2:'Two', 3:'Three', 4:'Four', 5:'Five', 6:'Six', 7:'Seven'}
}
print(my_dict0)
print(my_dict1)
print(my_dict2)
print(my_dict3)
print(my_dict4)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’}
{1: ‘North’, 2: ‘South’, 3: ‘East’, 4: ‘West’}
{‘North’: 1, ‘South’: 2, ‘East’: 3, ‘West’: 4}
{‘N’: ‘North’, 2: ‘South’, ‘East’: 3, ‘West’: ‘W’, ‘ComplexNumber’: (5+500j), 5.5: [1, 2, 3, 4]}
{‘Aphabets’: {‘A’: {‘Fruit’: ‘Apple’, ‘Object’: ‘Aeroplane’}, ‘B’: {‘Fruit’: ‘Banana’, ‘Object’: ‘Ball’}}, ‘Numbers’: {0: ‘Zero’, 1: ‘One’, 2: ‘Two’, 3: ‘Three’, 4: ‘Four’, 5: ‘Five’, 6: ‘Six’, 7: ‘Seven’}}

Other way to create dictionary to use the dict() constructor to make a dictionary:

sides = dict(N="North", S="South", E="East",W="West")
print(sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’}

Access elements from a dictionary

# Fetching dictionary values by key

print(sides['N'])
print(sides.get('S'))

North
South

# Nested Dictionary
my_dict = { 'Aphabets' : { 'A':{'Fruit':'Apple','Object':'Aeroplane'},'B':{'Fruit':'Banana','Object':'Ball'}} ,
'Numbers' : { 0: 'Zero', 1:'One', 2:'Two', 3:'Three', 4:'Four', 5:'Five', 6:'Six', 7:'Seven'}
}

smy_dict['Aphabets']['A']['Object']

‘Aeroplane’

my_dict4['Numbers'][5]

‘Five’

In Python dictionary no duplicate key is allowed.

# Creating a dictionary having duplicate keys

sides ={ "N": "East", "S": "South", "N": "West", "N": "North" }
print(sides)

{‘N’: ‘North’, ‘S’: ‘South’}

When duplicate keys found during dictionary creation, the last assignment is final one. See above example.

### Updating Dictionary

Adding a new key-value pair, modifying an existing key-value pair, or deleting an existing key-value pair.

# Creating a new dictionary

sides = dict(N="North", S="South", E="East",W="West")
print(sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’}

Adding a new key:value pairs to existing dictionary

sides['NE'] = 'North-East'
sides['NW'] = 'North-West'
print(sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’, ‘NE’: ‘North-East’, ‘NW’: ‘North-West’}

Updating key:value pair

sides['NE'] = 'North East'
sides['NW'] = 'North West'
print(sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’, ‘NE’: ‘North East’, ‘NW’: ‘North West’}

sides['NE']

‘North East’

Deleting an existing key:value pair

print(sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’, ‘NE’: ‘North East’, ‘NW’: ‘North West’}

del sides ['N'] # Remove the provided Key
print(sides)

{‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’, ‘NE’: ‘North East’, ‘NW’: ‘North West’}

del sides ; # delete dictionary completely

### Dictionary Methods

Python Dictionary provides so many methods. See below some examples

sides = dict(N="North", S="South", E="East",W="West")
print(sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’}

Get()

It return Value for Key.

print(sides.get('S'))

South

Items(), Keys () & Value()

Item – It return the list with all dictionary keys with values.
Keys – It return list of dictionary dict’s keys.
Value – It returns list of dictionary dict’s values.

print(sides.items())
print(sides.keys())
print(sides.values())

dict_items([(‘N’, ‘North’), (‘S’, ‘South’), (‘E’, ‘East’), (‘W’, ‘West’)])
dict_keys([‘N’, ‘S’, ‘E’, ‘W’])
dict_values([‘North’, ‘South’, ‘East’, ‘West’])

Copy()

It creates the copy of the dictionary into other dictionary.

new_sides = {}
new_sides = sides.copy()
print(new_sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’}

Update()

Adds dictionary key-values pairs to another dictionary.

sides = dict(N="North", S="South", E="East",W="West")
some_more_sides = dict(NE="North-East", SE="South-East")

print(sides)
print(some_more_sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’}
{‘NE’: ‘North-East’, ‘SE’: ‘South-East’}

sides.update(some_more_sides)
print(sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’, ‘NE’: ‘North-East’, ‘SE’: ‘South-East’}

Clear()

Removes all elements of dictionary.

some_more_sides.clear(); # Remove all entries in dictionary
print(some_more_sides)

{}


Thanks!

Happy Learning! Your feedback would be appreciated!

shobhitsingh.in

Github Code Link

Python [Post 05] | Lists

A list in Python is an ordered group of items. Items in a list need not be of the same type. A list is created by placing all the items inside a square bracket, separated by commas.

# Lists Examples

my_empty_list = []
number_list = [1,2,3,4,5]
str_list = ['A','B','C','D','Hello Python']
mix_list = ['A',1,'B',2,'C',12.5,5+500j]
nested_list = ['A',1,'B',2,['X','Y','Z']]
print(number_list)
print(str_list)
print(mix_list)
print(nested_list)

[1, 2, 3, 4, 5]
[‘A’, ‘B’, ‘C’, ‘D’, ‘Hello Python’]
[‘A’, 1, ‘B’, 2, ‘C’, 12.5, (5+500j)]
[‘A’, 1, ‘B’, 2, [‘X’, ‘Y’, ‘Z’]]

Some Built-in Python Functions

my_list = [1,2.5,3,4.6,5,6]

print(len(my_list)) # len Function - Gives the total length of the list.
print(max(my_list)) # max Function - Returns element from the list with maximum value.
print(min(my_list)) # min Function - Returns element from the list with minimum value.

6
6
1

### List Indexing & Slicing

Use the index operator [] to access an item in a list. We can use a : to perform slicing which extracts chunk of more than one element as per input. In slicing last index is not included.

sides = ['East','West','North','South']
# Fetch the first element of list sides

sides[0]

‘East’

# Fetch the last element of list sides

sides[-1]

‘South’

# fetch elements start from index 1st till last

sides[1:]

[‘West’, ‘North’, ‘South’]

# fetch elements upto 2nd index, but 2nd is not included

sides [:2]

[‘East’, ‘West’]

# fetch element from 1st index to 3rd index

sides [1:3]

[‘West’, ‘North’]

Unlike Python Strings, Python Lists are mutable i.e. the elements inside a list can be changed!

sides = ['East','West','North','South']
print(sides)

# Let's try to change the elements of lists sides

sides[0]= 3.0
sides[1]='Hello World'
sides[2]='Python World'
sides[3]= 12345

print(sides)

[‘East’, ‘West’, ‘North’, ‘South’]
[3.0, ‘Hello World’, ‘Python World’, 12345]

Nested Lists

A list inside a list.

some_sides = ['East','West','North','South']
more_sides1 = ['North-East','North-West']
more_sides2 = ['South-East','Soth-West']

nested_sides = [some_sides,more_sides1,more_sides2]

print(nested_sides)

[[‘East’, ‘West’, ‘North’, ‘South’], [‘North-East’, ‘North-West’], [‘South-East’, ‘Soth-West’]]

# Fetch the first element of first list

print(nested_sides[0])
print(nested_sides[0][0])

[‘East’, ‘West’, ‘North’, ‘South’]
East

# Fetch the second element of third list

print(nested_sides[2])
print(nested_sides[2][1])

[‘South-East’, ‘Soth-West’]
Soth-West

### Lists Methods

Python includes following list methods

# Creating a new list

sides = ['East','West','North','South']

Append():

Adds single element to the end of a list. Length of the list increases by 1 index.

# Example 1: Append Element in list

sides.append('North-East')
print(sides)

[‘East’, ‘West’, ‘North’, ‘South’, ‘North-East’]

# Other way to append

sides = sides + ['South-East','South-West']
print(sides)

[‘East’, ‘West’, ‘North’, ‘South’, ‘North-East’, ‘South-East’, ‘South-West’]

# Example 2: Append List with List (This will create nested list)

sides = ['East','West']
more_sides = ['North','South','North-East']

sides.append(more_sides)
print(sides)

[‘East’, ‘West’, [‘North’, ‘South’, ‘North-East’]]

Extend():

Add all elements of a list to the another list. It will not create nested list.

# Example - Extending Lists

sides = ['East','West']
more_sides = ['North','South','North-East']

sides.extend(more_sides)
print(sides)

[‘East’, ‘West’, ‘North’, ‘South’, ‘North-East’]

Insert():

Inserts an element at the position mentioned in its arguments. It takes two arguments, position and element.

# Example Insert

sides = ['West','North']

print(sides)

sides.insert(2,'South')
sides.insert(3,'South-East')
sides.insert(0,'East')

print(sides)

[‘West’, ‘North’]
[‘East’, ‘West’, ‘North’, ‘South’, ‘South-East’]

Pop():

Removes and returns an element at the given index. By default pop takes off the last index, but you can also specify which index to pop off.

sides.pop() # Pop off the last indexed item, by default

‘South-East’

print(sides)

[‘East’, ‘West’, ‘North’, ‘South’]

sides.pop(3) # Pop off the 3rd indexed item

‘South’

print(sides)

[‘East’, ‘West’, ‘North’]

Remove():

It is used to delete the first occurrence of item mentioned in its arguments.

sides = ['East','West','North','East','South']

sides.remove('East')
print(sides)

[‘West’, ‘North’, ‘East’, ‘South’]

Clear():

Removes all elements from the list.

sides = ['East','West','North','South']
print(sides)

[‘East’, ‘West’, ‘North’, ‘South’]

sides.clear() # Clear the list

print(len(sides))
print(sides)

0
[]

Index() :

Returns the index of the first matched item.

sides = ['EAST','West','North','East','South','East']

sides.index('East')

3

Count():

Returns the count of number of items passed as an argument.

sides.count('East')

2

Sort():

Sort items in a list in ascending order.

sides = ['West','North','East','South']

print(sides)
sides.sort()
print(sides)

[‘West’, ‘North’, ‘East’, ‘South’]
[‘East’, ‘North’, ‘South’, ‘West’]

Reverse():

Reverse the order of items in the list.

print(sides)
sides.reverse()
print(sides)

[‘East’, ‘North’, ‘South’, ‘West’]
[‘West’, ‘South’, ‘North’, ‘East’]


Thanks!

Happy Learning! Your feedback would be appreciated!

shobhitsingh.in

Github Code

Python [Post 04] | Strings

Folks,

In this blog post we will explore Python strings & string methods. Python strings are sequences of characters. Here are some examples of strings.

# Printing String

print('This is a string!') # Enclosed using single quote

print("This is also a string!") # Enclosed using double quote

print("""This is also a string,
also having next line.""") # Enclosed using triple quote. Multiple lines are generally put in triple quotes.

print("It's ok!") # Use double quote to enclose the string, if string is having single quote
print('P') # Python treat this single character also as string

This is a string!
This is also a string!
This is also a string,
also having next line.
It’s ok!
P

### String Indexing

Python strings are sequences of individual characters. We can access characters in strings by index. In Python index starts from 0, also if you want to start from the end, instead of the beginning then use a negative index.

Indexing Example: String x = ‘Python’

+ve Index 0 1 2 3 4 5
+ve Index 0 -5 -4 -3 -2 -1

# String Variable
x = 'Python'
x[0] # Fetch the first character of string x

‘P’

x[1] # Fetch the second character of string x

‘y’

x[-1] # Fetch the last character of string x

‘n’

Python strings are immutable. i.e. Once string is created, the elements within it can not be changed or replaced.

# Let's try to change the first letter to 'J' of string x
x[0] = 'J'

TypeError Traceback (most recent call last)

<ipython-input-6-5b400f918714> in <module>()
1 # Let’s try to change the first letter to ‘J’ of string x
—-> 2 x[0] = ‘J’

TypeError: ‘str’ object does not support item assignment

 

You can “update” an existing string by (re)assigning a variable to another string.

x = 'J' + x[1:]
print(x)

Jython

### Slicing Python String

We can use a : to perform slicing which extracts chunk of more than one character as per input. In slicing last index is not included.

String x = ‘Python’

+ve Index 0 1 2 3 4 5

+ve Index 0 -5 -4 -3 -2 -1

For Example:

# String Variable
x = 'Python'
x[0:2] # fetch the first 2 character of string x. x[0:2] is same as x[:2]

‘Py’

x[:3] # fetch the first 3 character of string x

‘Pyt’

x[2:5] # fetch character from 2nd index to 3rd index

‘tho’

x[2:] # fetch charcters start from index 2nd till last

‘thon’

x[:3] # fetch charcters upto 3rd index, but 3rd is not included

‘Pyt’

x[-5:-1] # Negative Index also works in slicing

‘ytho’

x[::] # fetch complete string

‘Python’

Skipping Characters using third parameter

x = 'Python'
x[::1] # Default is 1

‘Python’

x[::2] # Skip every 2nd character

‘Pto’

x[0:5:2] # Skip every 2nd character

‘Pto’

x[::-1] # Reverse String

‘nohtyP’

### String Methods Examples

Python String provides so many methods to do the string manipulations. See below examples.

# Split - Splits string as per provided delimiter ( default space) and returns list of substrings;

x = 'Python is fully-functional programming language that can do almost anything'
print(x.split())

[‘Python’, ‘is’, ‘fully-functional’, ‘programming’, ‘language’, ‘that’, ‘can’, ‘do’, ‘almost’, ‘anything’]

x = 'A,B,C,D,E,F'
print(x.split(',')) # Comma as delimeter

[‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’]

# Upper & Lower Case

x = 'Python'
print(x.upper())
print(x.lower())

PYTHON
python

# Checking String whether contains only alpha or numeric

x = 'Python3'
print(x.isalnum())
print(x.isalpha())
print(x.isnumeric())
len(x)

True
False
False
7

Lstrip, RStrip & Strip Method – For removing white spaces

# lstrip - Remove white space from left

x = ' Python3 '
x.lstrip()

‘Python3 ‘

# rstrip - Remove white space from left

x = ' Python3 '
x.rstrip()

‘ Python3’

# rstrip - Remove white space from left & right

x = ' Python3 '
x.strip()

‘Python3’

.format() String Method

Insert objects dynamically in the string using assigment keywords or index. It can also persorm alignment, padding & precision of floating point numbers.

import datetime
d = str(datetime.datetime.now())
# Example 1 -

x = "Today's date & time is {}"

x.format(d)

“Today’s date & time is 2018-07-08 02:04:47.893499”

# Example 2

x = "Today's date & time is %s" %datetime.datetime.now()

print(x)

Today’s date & time is 2018-07-08 02:04:49.885035

# Example 3

print('a {f} in need is a {f} indeed'.format(f='friend'))
print('a {0} in need is a {0} indeed'.format('friend'))

a friend in need is a friend indeed
a friend in need is a friend indeed

# String Formatting Operator - %
# Oldest method involves placeholders using the modulo % character. %s for string, %c is for character, %i integer, %f float etc

print('a %s in need is a %s indeed' %('friend','friend'))

x = "Today's date & time is %s" %datetime.datetime.now()
print(x)

x = "My name is %s, my age is %i & my height is %f" % ('John', 21, 150.56)
print(x)

a friend in need is a friend indeed
Today’s date & time is 2018-07-08 02:04:50.634701
My name is John, my age is 21 & my height is 150.560000

Precision of Float with .format() Method

You can add precision for float point numbers in string. See below example.

x = “My height is %5.1f” % (150.5678)

  • .1f stands for how many numbers to show past the decimal point.
  • 5 would be the minimum number of characters the string should contain. Padded with whitespace if the entire number does not have this many digits.
x = "My height is %5.1f" % (150.5678)
print(x)

My height is 150.6

x = "My height is %15.2f" % (150.5678)
print(x)

My height is 150.57

Padding & Alignment with .format() Method

# Padding

print('{0:5} | {1:3}'.format('FName', 'Age'))
print('{0:5} | {1:3}'.format('A', 14))
print('{0:5} | {1:3}'.format('B', 12))

FName | Age
A | 14
B | 12

By default, .format() aligns text to the left, numbers to the right.
Pass an optional <,^, or > to set a left, center or right alignment as per requirement.

# Alignment

print('{0:^5} | {1:^3}'.format('FName', 'Age'))
print('{0:^5} | {1:^3}'.format('A', 14))
print('{0:^5} | {1:^3}'.format('B', 12))

FName | Age
A | 14
B | 12

print('{0:-^10} | {1:-^10}'.format('FName', 'Age'))

–FName— | —Age—-

There are many more string methods eg. count, find, decode, encode, index etc.


Thanks!

Happy Learning! Your feedback would be appreciated!
shobhitsingh.in

[GitHub Code]

Python [Post 03] | Numbers

Folks,
In this blog we will explore different Python numeric types, arithmetic operations, mathematical fuctions, variable assignment & number conversion.

For Python Overview & Basic – Refer this Blog Post

Python has mainly three diffrent of numeric types.

  • int
  • float
  • complex

Integers (int)


Int/Integer, is basically a whole number (+ve or -ve), without decimals & of unlimited length.

Example of Integers: -5, 500, 20001543646546231654646465465454544545454554

 

# Integer Example 1
print(-5)
type(5)

-5
int

# Integer Example 2
print(500)
type(500)

500
int

# Integer Example 3
print(20001543646546231654646465465454544545454554)
type(20001543646546231654646465465454544545454554)

20001543646546231654646465465454544545454554
int

Float


Floating point numbers is a number, (+ve or -ve), represent real numbers and they have a decimal points in them, or use an exponential (e) to define the number.

Exampe of Floats: -5.5 , 500.5, 5E2

5E2 (5 times 10 to the power of 2) is also an example of a floating point number in Python.

# Float Example 1
print(-5.5)
type(-5.5)

-5.5
float

# Float Example 2
print(500.5)
type(500.5)

500.5
float

# Float Example 3
print(5E2)
type(5E2)

500.0
float

Complex Number


Numbers in the form of (a + bj), where a and b are floats and j represents the square root of -1. Real part of the number is a, and the imaginary part is b.

Exampe of Complex Number: 5+500j

# Complex Example 1
5+500j

(5+500j)

type(5+500j)

complex

Artithmetic Operations


# Additon of numbers
5+5

10

# Substraction of numbers
10-5

5

# Multiplication of numbers
10*5

50

# Division of nuumbers
10/5

2.0

# Floor Divison (// operator truncates the decimal without rounding)
10//4

2

# Exponent
5**2

25

# Modulus (% operator returns the remainder after division)
5%2

1

Mathematical Fuctions


Python also have some functions that perform mathematical calculations

# importing "math" for mathematical operations
import math
# Ceil Function
print (math.ceil(5.6))

6

# Floor Function
print (math.floor(5.6))

5

# Exponential Function
print (math.exp(5))

148.4131591025766

# Square Root Function
print (math.sqrt(16))

4.0

# Factorial Function
print (math.factorial(5))

120

# Absolute Function - Positive Number
print(abs(-5))

5

# Round Function - Number rounded to n digits from the decimal point
print(round(5.56))

# Round Function with 2nd argument for how many digits to round
print(round(5.56,1))

6
5.6

# Minimun Function - Finds smallest of its arguments
print (min(5,10,2,22))

2

# Mamimun Function - Finds largest of its arguments
print (min(5,10,2,22))

2

Variable Assignemnt


# Create an object/Variable called "length" and assign it the number 50
length = 50
print(length)

50

# Reassignment - Overrites value
length = 10
print(length)

10

length = 10
width = 5.6
height = 10.6

print(length * width * height)

593.6

Numerical Type Conversion


# Example 1:
height = 10.6
type(height)

float

# Let's convert this variable into int
height= int(height)
print(height)
type(height)

10
int

# Example 1:
length = 10
type(length)

int

# Let's convert this variable into foat
length= float(length)
print(length)
type(length)

10.0
float


Thanks!

Happy Learning! Your feedback would be appreciated!

shobhitsingh.in
Guthub Code