Handling arrays (lists) in Python

Arrays are one of the fundamentals in any programming language. However if you have used Python; for example, you may not find arrays in it. Instead you get list. It is a more general form of an array.

I prefer using NumPy library for handling arrays in real-time python developments. However it is required to have a basic knowledge of handling arrays in Python first.

List [ ]

List is a data structure that holds values of any type. It can be a collection of strings, integers or any other valid data type in python. They are dynamic (known as mutable too), meaning that you can add or delete values as you wish.

Define a List with [ ]

It is quite same as other languages, you can use [ ] to define a list.

newArray = []

or with values

newArray = ["Population","X","size",200,"size"]

As in arrays, the element counts starts from 0 and you can use “slicing” in Lists too.

print (newArray[2])

you may use the slicing to assign values to a List elements too.

newArray[2] = 100

You may notice that you can assign a new value and it can be in a different type.

Following is a python script showing things we discussed so far

newArray = ["Population","X","size",200,"size"]
print (newArray)
print ("Property of X = " + newArray[2])
newArray[3] = 200/3.5
print (newArray)

m-D List

It is possible to define multi dimensional lists and they behave quite similar to multidimensional arrays.

newArray = ["POST",["Status Code",100,200,300],["fail","pass","error"]]

you can use any combination of data types and any number of dimensions. Again slicing can be used to retrieve or assign values as we have observed above. Refer to the example code below:

newArray = ["POST",["Status Code",100,200,300],["fail","pass","error"]]
print (newArray[1][2])
newArray[2][1] = "Success"
print (newArray)

Associative Arrays in Python

However our goal in this post is to see how associative arrays can be handled in Python. In Python associated arrays are termed as dictionaries. Simply it is ordered key-value pairs.

How to define a dictionary:

dataArray = {"method":"POST", "action":"file.py", "status": 500}

So that later you can use the key value to retrieve the value of the element.


It is possible to use dict(sequence) function to create a dictionary too.

seq = (("method","POST"), ("action","file.py"), (2,500))

dataArray = dict(seq)

Values can be altered referring to the key value

seq = (("method","POST"), ("action","file.py"), (2,500))
dataArray = dict(seq)
dataArray[2] = 100
print (dataArray)

To delete an element, del(element) statement can be used.

seq = (("method","POST"), ("action","file.py"), (2,500))<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>
dataArray = dict(seq)
print (dataArray)

Methods on List

List data type has more methods that are very useful, will cover them briefly.

list.count(x) – Return the number of times value x appears in the list.

list.append(x) – Add element x to the list

list.extend(newList) – Extend the list by appending all the items in the newList

list.insert(n, x) – Insert the element x at n position. The current element at the position n will be moved backward.

list.remove(x) – Remove element which is the first item having the value x

list.pop([i]) – i is optional, remove the element in position i

list.index(x) – Return the index of the first element whose value is x in the list.

list.reverse() – Reverse the elements of a list

In the next part of the post will check how to implement basic data-structures such as stack and queue in python using lists.


Stack is analogous to a pile of books. The elements which goes last comes first. Therefore stack is a list where the index 0 of the list is the first element of the stack (this element will be the last element to be taken out).

stack = [1, 2, 3, 4]
#add elements to the stack
#taking elements out
x = stack.pop()


Not like stacks, in queues element which goes first come out first. Therefore it is possible to use pop() to retrieve values from a queue but when appending elements it should be placed at the beginning of the list. That is quite inefficient in lists as whole list should be shifted right to accommodate space to the new element.

It is recommended to use collections.deque in python for this purpose which is much more efficient.

However in this post will see how queues can be implemented using the knowledge we have gained so far.

queue = [4,3,2,1]
value = [5]
queue = value
print (queue)

Note that in the above example, the new value has been define as an element having one element. Otherwise it is not possible to use this technique.

Following is another way:

queue = [4,3,2,1]
print (queue)

Both techniques have 4 lines but I guess that the first method should be more efficient.

Will write on NumPy in the next post.


Overcoming the conventional stumbling block to global success

I do hope you will enjoy the following article as much as I did. May it be a motivation …

Dr. Sanjiva will be delivering “The IESL Ray Wijewardene Memorial Lecture – Nobody to Leader : Achieving Global Leadership with Software”, today (2017 Sep 7) at IESL. More Info…

a 22-year-old, ftesh out of university, can solve problrms but they haven’t seen many problems yet. You learn problems as yoh go along. The key to being a good entrepreneur is not about identifing problems but about caring enough to solve it.

Copyright Notice : This article appeared in DailyFT paper, 2017 Sep 6. http://www.ft.lk and I hold no copyrights. Shared with an intention to educate others. All rights reserved by the above named publication.

How to include PHPSecLib

I got an interesting question on my blog post, RSA cryptography in PHP (How To?). Even the example, I have provided works fine with the source I have provided, you would probably get into some issues when trying it from the scratch. Including PHPSecLib is not straight forward. You cannot just use include() or include_once() functions directly. It follows PEAR standard (PHP Extension and Application Repository), therefore you need to use the following trick if you dont have PEAR installed in your server or in your LAMP/ WAMP deployment.

For an example consider following directory structure:

------- App
+ ----------------- Core
+ ----------------- Vendors

Assuming that your code lies in the “Core” directory, and you are planning to place PHPSecLib in the “Vendors” directory, you can include the following to your code so that it will find the PHPSecLib without no issue:

$path = '../vendors/phpseclib/'; 
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

Working example:


$path = '../vendors/phpseclib/';
	set_include_path(get_include_path() . PATH_SEPARATOR . $path);

$rsa = new Crypt_RSA();
$keys = $rsa->createKey(2048);


$rsa->loadKey($keys['publickey']); // public key
$plaintext = 'I want to get encrypted !';

$ciphertext = $rsa->encrypt($plaintext);


$rsa->loadKey($keys['privatekey']); // private key
$text = $rsa->decrypt($ciphertext);

Note that we have explicitly defined the path for the library from the current directory where the executing script is located.

If you insist on using autoload instead, it can be achieved in the following manner. You cannot straight away let the autoload find the class as the file name and the class name are different. Therefore we need to change the path as the code can locate the Crypt_RSA class, which is ../vendors/phpseclib/Crypt/RSA.php


spl_autoload_register(function ($class_name) {
	$path = '../vendors/phpseclib/';
	set_include_path(get_include_path() . PATH_SEPARATOR . $path);
	include_once $class_name.'.php';

$rsa = new Crypt_RSA();
$keys = $rsa->createKey(2048);


$rsa->loadKey($keys['publickey']); // public key
$plaintext = 'I want to get encrypted !';

$ciphertext = $rsa->encrypt($plaintext);


$rsa->loadKey($keys['privatekey']); // private key
$text = $rsa->decrypt($ciphertext);

Hope you will find this information useful. Cheers !!

How to store keys (RSA) ?

The last post was about handling RSA cryptosystem in PHP. This post is covering a small aspect of the last post.

Once keys (Public and Private) are generated there should be a method of storing the keys, both private and the public keys to use later. Since the keys are having a specific format you are not able to store them in a raw format. It doesn’t work the next time when you try to use them.

There are few formats and methods we can use. In the last post, the generated keys are in PEM (Privacy Enhanced Mail) format. Dont get confused with that. I am suggesting a technique to store the keys. There are many other ways to get this accomplished. Among them base64 encoding/ decoding would be quite handy and easy.

PEM formatted private key is noted below.

Proc-Type: 4,ENCRYPTED


Base64 encoded key (note that it appears as a single line, no line breaks).


You can simply use a “TEXT data typed” filed in MySQL table to store base64 encoded key pair and then when it is needed just base64 decode and use it. Even you can apply further encryption against the base64_encoded string to make the key much more secure. You can hash the base64_encoded string and create signatures of the keys as another security measurement.

Simply use the base64_encode( ) and base64_decode( ) functions in PHP.

$encoded_key = base64_encode(myRSA::$privateKey);

$private_key = base64_decode($encoded_key);

NOTE: base64 encoding doesn’t provide any additional security, it is purely assisting towards storing/ passing the keys in a more comfortable way. Therefore you need to use an additional security layer (eg: database data encryption) on top of the stored keys to make it much more secure.

RSA cryptography in PHP (How To?)

Being security is one of the utmost considerations in current web site/ application development process, I am sure you have spent a lot of time writing codes to handle encryption in your applications.

In this article I am trying to present one of my favorite ways to solve this issue, the RSA encryption/ decryption handling in your PHP development.

This is quite straight forward as I am using PHPSecLib package. I was using openSSL library for PHP for few years and recently started dealing with this package. It is pretty cool implementation so I started loving it.

First of all you need to get the package, it is available to download[1] and it comes with MIT license[2], GPL compatible[3].

If your intention is to use PHPSecLib only for RSA encryption and decryption I suggest including only two directories which are Crypt and Math in your production environment.

First step towards the RSA encryption is to create the public and private keys. Note that I have secured the keys with a passphrase.

$rsa = new Crypt_RSA();

echo $keys['privatekey'];
echo $keys['publickey'];

The code is self explaining. createKey() method is taking the bit value of the key and output an array which contains the Private and Public keys. setPassword() is optional, you can omit it if you dont want to create the keys with a passphrase. If you want to use 2048 bit key then provide 2048 as an argument in createKey() instead 1024.

Once keys are ready you can start the encryption. I am using using the public key. Passphrase is not required when encrypting.

$plaintext = 'Text to be transmitted securely !!!';
$ciphertext = $rsa->encrypt($plaintext);
echo $ciphertext;

Decryption goes as follow (using the private key), note that the passphrase is mandatory:

$re_plaintText =  $rsa->decrypt($ciphertext);
echo $re_plaintText;

I have written a static class to demonstrate how encryption can be carried out. Please check the following:

***DO NOT use this code in your production env as the code lacks lot of fine tuning and security measures***

This is just to illustrate how the PHPSecLib can be used in a code



class myRSA
	public static $privateKey = '';
	public static $publicKey = '';
	public static $keyPhrase = '';
	public static function createKeyPair()
		$rsa = new Crypt_RSA();
		$password = base64_encode(sha1(time().rand(100000,999999)));
		$rsa->setPassword($password );

	public static function encryptText($text)
		$rsa = new Crypt_RSA();
		$encryptedText = $rsa->encrypt($text);
		return $encryptedText;

	public static function decryptText($encryText)
		$rsa = new Crypt_RSA();
		$plaintext = $rsa->decrypt($encryText);
		return $plaintext;


//create keys

//Text to encrypt
$text = "A secret lies here, send the text via a secure mode";
echo 'Text : '.$text;

$secureText = myRSA::encryptText($text);
echo 'Encrypted : '.$secureText;

$decrypted_text =  myRSA::decryptText($secureText);
echo 'Decrypted Text : '.$decrypted_text;

PHPSecLib API Documentation is available here.[4] A handy reference to check when you get stuck or need more info on methods.

[1] http://phpseclib.sourceforge.net/index.html

[2] https://en.wikipedia.org/wiki/MIT_License

[3] https://www.gnu.org/licenses/license-list.html#X11License

[4] https://api.phpseclib.org/master/

Think before calling an unknown number, you will be hacked ?

Interesting security advice is being circulated these days. It says;

Apparently “many are getting a missed call from the number +17675027697. Looks like a virus where calling back this number might hack your phone or something. Be Careful !

Can this be true?

When you got a missed call, you might call the number and check who the hell it is. Or at least you in return make another missed call. Can this act lead to a hacking of your mobile? Indeed NO, it is not possible. So you can rule out the risk of being hacked. In that context the message is a bloody hoax. But yes there is a BUT, there are some risks. In fact a social engineering attacks. Being more specific, a type of vishing[1].

Well first, the attackers can deceive you with a recording, imitating that you have reached to a lottery or a draw and you have won a grand prize (most probably some dollars) and then you will be directed through some menu options to select this and that and finally may ask for you credit card details (or some personal information such as social security number{NIC in SL} etc) and so on. Or else even it is possible to request your details such as email address via voice, so that the bot can record it and convert to text. There can be endless possibilities but the main motive is to collect your personal and/or financial information.

When you respond calling back the attacker, it get to know your phone number is real. That means he earns a real phone number. Real phone numbers are expensive than a real email. He can sell it for a good price in deep web. Advertisers or even hackers are interested in such info as they can flood you with advertisements or use social engineering to exploit more info from you. What if you provide your personal info such as age, city you are live in etc. A partially complete profile of you.

Other than that an attacker can do nothing. He cannot hack you via a call as there is no way to access your mobile phone OS or any other installed application via a phone call (unless you use such an app or an OS which enables such, surely not Android nor iOS). But if your mobile is infected with a virus that enables such functions, need not to mention that, you are in a grave. But in that case I dont think the attacker will use such a dumb technique to gain control. He can simply connect the phone via internet and access your mobile and check what you are doing via the phone’s camera. Sounds like a sci-fi movie scene but this is 100% practical and possible.

No party can charge you an extra amount (other than the standard tariffs) for the call you make, unless there is an pre-agreed agreement. Even the carrier itself cannot subscribe you to a service and charge you because you called a number. If such things in place you need to be informed once the call has been answered and seek your consent/ verification to move forward.

Finally, the message seems quite exaggerated. But better you refrain calling unknown numbers, doesnt matter local or foreign. Even you called back do not give any private information unless the person on the other side is verified, May be you are not going to provide any information but simply calling back the number and hanging the line (another missed call by you in that case) hints that your mobile number is real. You may be a target of a bot generating random phone numbers with miss calls and then try to check if the number is real.

Better you worry about above facts rather than worrying about getting your phone hacked.

Ref 1 : https://en.wikipedia.org/wiki/Voice_phishing

Time Zone Conversions (after Google lies)

Google is at my disposal, easy to use and pretty accurate. Hence I use Google frequently to check time in other countries and also use it pretty much to convert time. However once Day Light Saving (DST) has started the time conversion seems to be not correct,

For an example, the time difference is 3.5 hrs in CET to IST when DST is in effect. But Google still thinks the difference is 4.5 hrs.


Search Link

I prefer www.timeanddate.com which is one of the best tools to work with time zones. Time zone conversion is pretty handy, I would say it is pretty CooL.

Having said that, I also came across WolframAlpha.com which is handy and smart as well.


Search Link

WolframAlpha is amazing, it comes with some useful tools.


I played with few and still exploring the other tools. Firefox add-on, Chrome extension are also available. Just give it a try. You wont get regret, I m pretty sure.

PS: found the following article when I google – Google Lies, pretty funny and interesting, have a look guys !