Posts Tagged ‘array’

A Tour On Python List

Posted: May 28, 2015 in Programming
Tags: , , ,

 For those who have used Arrays in C and C++, list in Python is going to be a lucky charm . As Head First Python states, List is nothing but an array with steroids. Python list makes the life very easier as its dynamic in nature and the in-build functions are available to perform all the actions on it.

First lets list down the basic stuffs that we always do on arrays .

1. Declaring
2. Creating
3. Initializing with predefined input
4. Adding More input to it
5. Searching
6. Indexing
7. Removing
8. Erasing
9. In Built Functions

In this tutorial, am going to use 2 lists. One named numbers and other named alphabets. Lets go and see one by one .

1. Declaring a list

As we know, we need not declare a variable with appropriate data type in python . both a = 5 and a = ‘5’ are valid without specifying the corresponding data type. And more importantly, its applicable to lists as well.

2. Creating a list

When i say creating , it has 2 modes. Creating an empty one to add items later. Or creating a predefined set of elements in the list. To create an empty list, all we need to do is to write an open and closed square brackets.

numbers = []

https://shrinathsuccess.files.wordpress.com/2015/05/list2.png?w=614

3. Initializing with Predefined Input:

Sometimes, we will be really sure that we are going to work with only some specific inputs. In those situations we can create a list with pre defined inputs in it. That can be done by enclosing the inputs inside the square bracket

numbers = [1,2,3,4]

https://shrinathsuccess.files.wordpress.com/2015/05/list3.png?w=614

4. Adding more input to a List:

Adding input to the list can be categorized as following

4.1 – Adding elements one by one to a list
4.2 – Adding elements in a block
4.3 – Multiplying the list
4.4 – Adding list inside a list

4.1 – Adding elements one by one to the list :

Python has predefined function named “insert” , which can be used to add elements to the list. However, the insert takes two arguments. first one is the position and second one is the value. The list with numbers 1,2,3,4 can also be created as below

numbers = []
numbers.insert(0,1)
numbers.insert(1,2)
numbers.insert(2,3)
numbers.insert(3,4)

https://shrinathsuccess.files.wordpress.com/2015/05/list4-1.png?w=614

4.2 – Adding elements in block

If suppose we have 2 lists. first one containing numbers 1 to 3 and other one containing numbers 4 to 6. And we need to merge two list. ie. adding elements in block, then we can do it as below:

num1 = [1,2,3]
num2 = [4,5,6]
num1 + num2

or simply

[1,2,3] + [4,5,6]

https://shrinathsuccess.files.wordpress.com/2015/05/list4-2.png?w=614

4.3 – Multiplying the list

Python creates a easy way of inserting repeated items. For example, if we need a list which has 3 numbers 1,2,3 ten times. we need not write a for loop . Just a simple multiplication operator on list will do it as below

numbers = [1,2,3]
numbers * 10

https://shrinathsuccess.files.wordpress.com/2015/05/list4-3.png?w=614

4.4. Nesting Lists

Yes, we can have list inside a list. And there is a specific way for indexing the list. In the list below , 4th item is a list which contains 3 items in turn.

numAlpha = [1,2,3 [ “a”, “b”, “c” ]]

https://shrinathsuccess.files.wordpress.com/2015/05/list4-4.png?w=614

5. Searching an element in the list

If we need to check an element exists in the list , we can use “in” keyword with list which will return a boolean value (True indicating the element exists and false indicating the element doesnt exist in the list)

numbers = [1,2,3,4,5,6]
4 in numbers
7 in numbers

https://shrinathsuccess.files.wordpress.com/2015/05/list5.png?w=614

6. Indexing list

We can get the element based on the index of that element in the list. Since, all the elements are inserted into the list with the index element, we can derive any element if we know the index. Index starts with 0 and moves on as we insert the elements.

List_name[start : end]

This is the common notation . start denotes the starting index that we need to start with, to start from beginning give 0 or leave it empty. End denotes the position to which list should print

numbers = [1,2,3,4,5,6]
numbers[1:4] - show elements from index 1 till 3
numbers[:2] - show elements from beginning till 1st index
numbers[2:] - show elements from index 2 to end of the list
numbers[:] - print all elements
numbers[-2] - tricky one .. show 2nd last element in the list

https://shrinathsuccess.files.wordpress.com/2015/05/list6.png?w=614

7. Removing elements from a list :

We can remove an element from the list if we know the index or element value. remove function can be used if we know the list value and del function can be used to remove using index.

numbers = [1,2,3,4,5,6]
numbers.remove(5)
numbers
del numbers[-4]
numbers

https://shrinathsuccess.files.wordpress.com/2015/05/list7.png?w=614

8. Erasing the list :

If we need to erase all the elements in the list , we can use clear function . List_name.clear() will remove all the elements from list.

numbers = [1,2,3,4,5,6]
numbers.clear()
numbers

https://shrinathsuccess.files.wordpress.com/2015/05/list8.png?w=614

9. Inbuilt Functions :

There are lot of inbuilt functions available in python list. One that we saw is len(list_name) which gives the length . Similarly we have

len – finds the total number of elements in the list
count – finds the number of occurrence for an element
sort – sorts the list
reverse – reverse the list
index – returns the index of first matching element

https://shrinathsuccess.files.wordpress.com/2015/05/list9.png?w=614

Advertisements

Being new to perl, array handling through functions seem to be bit difficult. Thought of sharing some possible ways of handling array between the functions.

1. Call by Value

In call by value the changes inside the function wont reflect back.. As you see in the program

size of arr – 1
size of arrnew – 2 ( since the value of arr is passed to this array. The value persist only in function scope)

#!/usr/bin/perl

my @arr = ();
push @arr,"1";
&fun(@arr);
print scalar(@arr);

sub fun()
{
my @arrnew = shift;
push @arrnew,"2";
print scalar(@arrnew);
}

2. Call by reference

In call by reference , the changes made in the function reflects back. Use “\” operator before passing array and whenever we deal with the element of the array we need to add $ to it.. (@$arr).. Here

Size of arrnew is 2

Size of arr is also 2 ( since the changes reflects back)

#!/usr/bin/perl

my @arr = ();
push @arr,"1";
&fun(\@arr);
print scalar(@arr);

sub fun()
{
my $arrnew = shift;
push @$arrnew,"2";
print scalar(@$arrnew);
}

3. Return as array

Once the changes are done, the return value is passed as array.

size of arr – 1
size of arrsub – 2 (modified inside the function)
size of newarr – 2 ( its the return value of arrsub)

#!/usr/bin/perl

my @arr = ();
push @arr,"1";
my @newarr = ();
@newarr = &fun(@arr);
print scalar(@newarr);

sub fun()
{
my @arrsub= shift;
push @arrsub,"2";
print scalar(@arrsub);
return @arrsub;
}

When the size of an array is unknown at the run time we need to create dynamic array. In java there

are plenty of ways in which we can build array dynamically . In that, i am choosing one of the easy way.

It’s through ‘Arraylist’. Here we will take a tour from ‘How to create an Arraylist’ to ‘How to use

arraylist’.

Syntax for creating an arraylist is

ArrayList arraylist_name = new ArrayList();

Here is a simple code which creates an arraylist named fruits and adds fruit names to it.

import java.util.ArrayList; 
public class fruits {

	public static void main(String[] args) {

		ArrayList fruits = new ArrayList(); //creating a new arraylist
		fruits.add("apple"); // adding fruit names to it
		fruits.add("orange");
		fruits.add("mango");
	}
}

okay, now we have created an arraylist..Now, lets see how many elements we have added to it. Use size()

function to get the size of it.

import java.util.ArrayList;
public class fruits {

	public static void main(String[] args) {

		ArrayList fruits = new ArrayList(); //creating a new arraylist
		fruits.add("apple"); // adding fruit names to it
		fruits.add("orange");
		fruits.add("mango");
		System.out.println("The size of fruit array list is" + fruits.size());
	}
}

now, we know that we have added 3 elements in the array. What are all those elements? Know it by

fetching the ArrayList items.

Here i gonna show retrieval process in 2 different types

1. We can make use of an utility called Iterator which will point to the array list item and we can fetch

using the function next();

import java.util.ArrayList;
import java.util.Iterator;


public class fruits {

	public static void main(String[] args) {

		ArrayList fruits = new ArrayList();
		fruits.add("apple");
		fruits.add("orange");
		fruits.add("mango");
		System.out.println(fruits.size());
		 Iterator itr = fruits.iterator();
		 while(itr.hasNext()) // loop thro elements
			 System.out.println(itr.next()); //print the element itr pointing to
				
	}
}

2. we can also use the for loop to retrieve the items by using the function get()

import java.util.ArrayList;
import java.util.Iterator;


public class fruits {

	public static void main(String[] args) {

		ArrayList fruits = new ArrayList();
		fruits.add("apple");
		fruits.add("orange");
		fruits.add("mango");
		System.out.println(fruits.size());
		 for(int i=0;i<fruits.size();i++) // run loop till size of arraylist
			 System.out.println(fruits.get(i)); // print array using get method		
		
	}

}

now, consider i need get the item in the second position. Then how could i do that? Its so simple. We

know the index. Just put it in the get method;

import java.util.ArrayList;
import java.util.Iterator;


public class fruits {

	public static void main(String[] args) {

		ArrayList fruits = new ArrayList();
		fruits.add("apple");
		fruits.add("orange");
		fruits.add("mango");
		System.out.println(fruits.size());
		System.out.println(fruits.get(1)); // print second element in array		
		
	}

}

Note: The array index starts from 0. Hence for second element in array , the index will be 1

When we use dynamic array, the size of the array can be changed right ? So, consider we need to insert

a new fruit named ‘grape’. But we need to put it in between apple and orange. How could we do that?

import java.util.ArrayList;
import java.util.Iterator;


public class fruits {

	public static void main(String[] args) {

		ArrayList fruits = new ArrayList();
		fruits.add("apple");
		fruits.add("orange");
		fruits.add("mango");
		fruits.add(1,"grape"); // adding element in the index 1 i.e adding as second element 
		System.out.println(fruits.size());
		for(int i=0;i<fruits.size();i++)
			 System.out.println(fruits.get(i));
		
	}

}

when we can add element in between an array, we can also delete the element. Do it be specifying the

index or by the element name itself.

import java.util.ArrayList;
import java.util.Iterator;


public class fruits {

	public static void main(String[] args) {

		ArrayList fruits = new ArrayList();
		fruits.add("apple");
		fruits.add("orange");
		fruits.add("mango");
		fruits.remove(0); // remove the first element
		fruits.remove("grape"); // remove the element named grape
		System.out.println(fruits.size());
		for(int i=0;i<fruits.size();i++)
			 System.out.println(fruits.get(i));
		
	}

}

Till now we went through the process of insertion and deletion. Here comes the datatype. We can store

different data types in Arraylist. Lets see one by one.

1. Storing boolean type in ArrayList

import java.util.ArrayList;
import java.util.Iterator;


public class fruits {

	public static void main(String[] args) {
		
		ArrayList<Boolean> arrayList = new ArrayList<Boolean>();
		arrayList.add(true);
		arrayList.add(false);
		arrayList.add(true);
		arrayList.add(false);
		 for(int i=0;i<fruits.size();i++)
			 System.out.println(arrayList.get(i));
				
	}

}

2. Storing Integer Datatype

import java.util.ArrayList;
import java.util.Iterator;


public class fruits {

	public static void main(String[] args) {
		
		ArrayList<Integer> arrayList = new ArrayList<Integer>();
		arrayList.add(1);
		arrayList.add(2);
		arrayList.add(3);
		arrayList.add(4);
		 for(int i=0;i<fruits.size();i++)
			 System.out.println(arrayList.get(i).intValue());
				
	}

}

while using Integer datatype we need to be careful while retrieving.. If we are retriving like arraList.get

(i), we wont get the integer number. Hence, to convert it into primitive int we need to add get.intValue()

3. Storing Strings in arraylist

import java.util.ArrayList;
import java.util.Iterator;


public class fruits {

	public static void main(String[] args) {

		ArrayList<String> fruits = new ArrayList<String>();
		fruits.add("apple");
		fruits.add("orange");
		fruits.add("mango");
		System.out.println(fruits.size());
		 for(int i=0;i<fruits.size();i++) 
			 System.out.println(fruits.get(i));
		
	}

}