Showing posts with label array. Show all posts
Showing posts with label array. Show all posts

Jun 3, 2021

Python Array Vs List

 Python Array Vs List

ListArray
Heterigenous elements
E.g, [1, 2, [3, 4], 5, 6]
Homogenous elements
numbers = array.array('i', [1, 2, 3])
Explicitly define type of elements while defining (i - means integers
Use lot more spaceUse less spcace compared lists
List contains pointers to different objectsLike C language arrays, with a pointer pointing to first element & rest are allocated in continuous memory
More flexible keeping different structures of dataLess flexible
Less efficient in storing & manipulatingMore efficient in storing & manipulating
Used when your collection grow & shrink in time efficient manner & manage lot of data types in a listUsed when you perform lot of computationally intensive math operations
Numpy arrays are more suited for mathematical operations



Python Arrays

Arrays are sequence of homogeneous elements

import array

numbers = array.array('i', [1, 2, 3])

numbers.append(4)
print(numbers) # array('i', [1, 2, 3, 4])

# extend() appends iterable to the end of the array
numbers.extend([5, 6, 7])
print(numbers) # array('i', [1, 2, 3, 4, 5, 6, 7])


May 19, 2020

Python List Vs Array

# Arrays Vs Lists
  • Arrays need to be declared. Lists don’t
  • Arrays can store data very compactly
  • Arrays are great for numerical operations

import array

# Array (stores single data type)
array.array('i', [1, 22, 30, 44, 51]) # integer
array.array('d', [2.5, 3.2, 3.3]) # float
array.array('u', ['a', 'b', 'c']) # unicode

#List
ll = ['abc', 10, ['a', 'b', 'c'], (1,2,3)] # List can store anything 


import numpy as np

# Numpy Array (it can store various data types)
array_2 = np.array(["numbers", 3, 6, 9, 12])
print (array_2)
print(type(array_2))





 

Jun 28, 2013

Delete element from Array in Perl

You can use 'delete' command for deleting an element from an array.
When you delete an element from the middle of an array, that particular elements is undef (ie., not defined)

Please refer to the below program:

#!/usr/bin/perl 

use strict;
use warnings;
use Data::Dumper;

my @array = qw/10 20 30 40 50/;

print "\n Before Deleting :" . Dumper(\@array);

delete $array[2];

print "\n After Deleting :" . Dumper(\@array);
  

Output:

Before Deleting :$VAR1 = [
          '10',
          '20',
          '30',
          '40',
          '50'
        ];

 After Deleting :$VAR1 = [
          '10',
          '20',
          undef,
          '40',
          '50'
        ];
  


Jun 11, 2013

Shift Unshift in Perl

Shift/Unshift => It works at the start of the array

Shift     => It removes element from start of an array
Unshift => It appends element to start of an array

use strict;
use warnings;

my @names = ("Foo", "Bar", "Baz");

print "\n Array : " . Dumper(\@names);

my $first = shift @names;     #Shift - removes element at the start of the array

print "$first";               #Foo
print "\n After Shift : " . Dumper(\@names);   #Bar Baz

unshift @names, "Moo";         # UnShift - adds element at the start of the array
print "\n After UnShift : " . Dumper(\@names);   # Moo Bar Baz  

Push Pop in Perl

Push/Pop      => It works at the end of the array
Push => Appends an element to end of an array
Pop  => Deletes an element from end of an array

@myNames = ('Larry', 'Curly');
push(@myNames, 'Moe');     #It adds 'Moe' at the end of the array

O/P: ('Larry', 'Curly', 'Moe')


@myNames = ('Larry', 'Curly', 'Moe');
$oneName = pop(@myNames);  #It removes 'Moe' from the end of the array

O/P: ('Larry', 'Curly')  

Delete an entry in Array and Hash in Perl

Let's discuss about deleting an element in array and hash respectively.

Deleting an element from an array:
use strict;
use warnings;

use Data::Dumper;

my @array = qw/10 20 30 40 50/;

print "\n Before Deleting :" . Dumper(\@array);

delete $array[2];

print "\n After Deleting :" . Dumper(\@array); 

Output:
Before Deleting :$VAR1 = [
          '10',
          '20',
          '30',
          '40',
          '50'
        ];

 After Deleting :$VAR1 = [
          '10',
          '20',
          undef,
          '40',
          '50'
        ];
 


Deleting an element from Hash:
use strict;
use warnings;

use Data::Dumper;

my %hash = ( a => 10, b => 20, c => 30, d => 40);

print "\n Before Deleting : " . Dumper(\%hash);

delete $hash{a};

print "\n After Deleting : " . Dumper(\%hash);

Output:
Before Deleting : $VAR1 = {
          'c' => 30,
          'a' => 10,
          'b' => 20,
          'd' => 40
        };

 After Deleting : $VAR1 = {
          'c' => 30,
          'b' => 20,
          'd' => 40
        };
  


Jun 22, 2008

Array in Perl

Array:

Its a sequenced list of elements.
Array index starts with zero.

use strict;
use warnings;
use Data::Dumper;

my @arr = ("Mother Teresa", "Abraham Lincoln", "Winston Churchill", "Mahathma Gandhi");

print "\n Print Array Values just like that : @arr";

print "\n\n Print Array Values with Dumper : " . Dumper(\@arr);


my @num_arr = qw/100 200 300/;

print "\n First Val : " . $num_arr[0];

print "\n";

Outout :

 Print Array Values just like that : Mother Teresa Abraham Lincoln Winston Churchill Mahathma Gandhi

 Print Array Values with Dumper : $VAR1 = [
          'Mother Teresa',
          'Abraham Lincoln',
          'Winston Churchill',
          'Mahathma Gandhi'
        ];

 First Val : 100
  


Please refer to other topics in Perl like :
How to read command line arguments in Perl
How to pass command line arguments to perl script
Loop through Directory and read the files in Perl
How to create excel report in Perl


Please refer to other topics on Unix like :
Unix Delete Duplicated Lines in a File
Unix Unique Lines in a File
Unix Grep Examples
Unix Cut Command Examples
Search a Directory in Unix
Unix For Loop
pushd & popd in Unix
Find Size of Directory
Word Count


Please refer to other topics on AWK like :
Awk Examples
Print First Two Columns of File
Print Last Two Columns of File


Please refer to other topics on Dict like :
Dict in Python
Dict keys and values in Python


Please refer to other topics on List like :
List in Python
Append to list in Python
Delete the last name from the list in Python
Remove an element from List in Python
Check an element exists in an list in Python
Python Filter Vs Map Vs List Comprehension


Please refer to other topics on File Concepts like :
Print File Content in Python
Print File in Reverse Order in Python


Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl


You might also wish to read other topics on Python like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton


Scalar

Scalar : 

In Perl, scalar can store a single value at any time.
In the following example, $str contains a string value.
We can store any single integer, string, float value in a scalar. It's as simple as that.

E.g., $str1 = 100;
        $str2 = 'test';
        $str3 = 300.2;


use strict;
use warnings;
use Data::Dumper;

#In Perl, scalar can store a single value at any time.
#In the following example, $str contains a string value.
#We can store any single integer, string, float value in a scalar. It's as simple as that.


#Integer
my $num = 300;
print "\n Number : " . $num;

#String
my $str = "Alex Perter John Dane";

#Array
my @arr = split(/ /,$str);

print "\n After Split : " . Dumper(\@arr);
  

Output:
 Number : 300
 After Split : $VAR1 = [
          'Alex',
          'Perter',
          'John',
          'Dane'
        ];


Please refer to other topics in Perl like :
How to read command line arguments in Perl
How to pass command line arguments to perl script
Loop through Directory and read the files in Perl
How to create excel report in Perl


Please refer to other topics on Unix like :
Unix Delete Duplicated Lines in a File
Unix Unique Lines in a File
Unix Grep Examples
Unix Cut Command Examples
Search a Directory in Unix
Unix For Loop
pushd & popd in Unix
Find Size of Directory
Word Count


Please refer to other topics on AWK like :
Awk Examples
Print First Two Columns of File
Print Last Two Columns of File


Please refer to other topics on Dict like :
Dict in Python
Dict keys and values in Python


Please refer to other topics on List like :
List in Python
Append to list in Python
Delete the last name from the list in Python
Remove an element from List in Python
Check an element exists in an list in Python
Python Filter Vs Map Vs List Comprehension


Please refer to other topics on File Concepts like :
Print File Content in Python
Print File in Reverse Order in Python


Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl


You might also wish to read other topics on Python like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton


Get unique elemenets from Arrays

#!F:\Perl\bin\perl -w
use Data::Dumper;
use strict;

#unique elements from different arrays
my @array1 = (10,20,30);
my @array2 = (11,22,33);
my @array3 = (10,20,30);
my %uniq_arr;

for my $each (@array2, @array3, @array1) {
$uniq_arr{$each}++;
}
print "\n", $_ for (keys %uniq_arr),"\n";

Sort an Array

1) For number Array

#!F:\Perl\bin\perl -w
use Data::Dumper;

my @array = (20,10,50,40,30); #Unsorted Number Array
print "\n Unsorted Array is: @array";
my @sorted = sort { $a <=> $b } @array;

# '<=>' for numbers only
# 'cmp' used for numbers as well as strings
print "\n sorted Array is: @sorted";
my @sorted = sort { $a cmp $b } @array;

print "\n sorted Array is: @sorted";


2) For String Array

#!F:\Perl\bin\perl -w
use Data::Dumper;
#Unsorted String Array
my @array = qw/sandhya eswar prabhath vamsi/;
print "\n Unsorted Array is: @array";

my @sorted = sort { $a cmp $b } @array;

# 'cmp' can be used for both strings as well as numbers
print "\n sorted Array is: @sorted";

Get a Random element from an Array

#!F:\Perl\bin\perl -w
use Data::Dumper;

my @array = (10,20,30,40,50);
#'rand' gives some random index number
$index = rand @array;
print "\n Random index from an array is:", $index;
$element = $array[$index];
print "\n Random element from an array is:", $element,"\n";

Different ways to remove duplicates from array

#!F:\Perl\bin\perl -w
use strict;
use Data::Dumper;

#Remove duplicates from array.
my @array = qw/10 20 20 20 30 40 40 40 50 50 50/;
print "\n Duplicate array: @array";

1) Good

my %hash;
$hash{$_} = 0 for (@array);
# $hash{$_} = () for (@array); #You can do this also

my @final = keys (%hash);
print "\n Unique Array: @final";
print "\n";


2) Best of all

my %hash = map { $_ , 1 } @array;
my @uniq = keys %hash;
print "\n Uniq Array:", Dumper(\@uniq);


3) Costly process as it involves 'greping'

my %saw;
my @out = grep(!$saw{$_}++, @array);
print "\n Uniq Array: @out \n";

How to create an unique array

#!F:\Perl\bin\perl -w
use Data::Dumper;

my @array_with_duplicate_elements = qw/ 1 2 3 4 5 5 5 5 4 4 4/;
my %hash = map { $_, 1 } @array_with_duplicate_elements;
my @unique_array = keys %hash;
print Dumper(\@unique_array);

Find difference, union and intersection of two arrays

#!F:\Perl\bin\perl -w

use Data::Dumper;
@union = @intersection = @difference = ();
%count = ();

#Make sure that both arrays are unique
my @array1 = (10, 20, 30, 40, 50, 60);
my @array2 = (50, 60, 70, 80, 90, 100);

foreach $element (@array1, @array2) { $count{$element}++ }

#print "\n all values hash:", Dumper(\%count);

foreach $element (keys %count) {
push @union, $element;
push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;
}


print "\n Union values:", Dumper(\@union);
print "\n Intersection Values:", Dumper(\@intersection);
print "\n Difference Array:", Dumper(\@difference);
print "\n";

compare two arrays

#!F:\Perl\bin\perl -w
use Data::Dumper;

my @array1 = ('a','b','c','d','e');
my @array2 = ('a','b','c','d','e');

if ( @array1 == @array2) {
print "\n equal";
} else {
print "\n not equal";
}

Difference between array and array reference

#!F:\Perl\bin\perl -w
use strict;

my $array = [ qw/sandhya prabhath eswar vamsi/];
print $array[0]; # Throws error since $array is a reference, you can't accesss directly
print $array->[0]; # sandhya

my @arr = qw/ 100 200 300/;
print $arr[0]; # Now you cn access as usual, since it is an array