Sunday, February 2, 2020

List Manipulations - Methods


List have many different methods . Some of that are available with list object in Python programming are:



index() 
In simple terms, the index() method finds the given element in a list and returns its position. If the same element is present more than once, the method returns the index of the first occurrence of the element.

The syntax of the index() method is:
list.index(element)


Example
p = ['p', 'r', 'o', 'g', 'r', 'a', 'm']
index = p.index('o')
print('The index of o:', index)
index = p.index('r')
print('The index of r:', index)

Output
The index of o: 2
The index of r: 1
---------------------------------------------------------------------------------------------------------------


append()
To add an item to the end of the list, use the append() method.
The syntax of the append() method is:
list.append(item)

Example
list = ["aaa", "bbb", "ccc"]
list.append("ooo")
print(list)

Output
['aaa', 'bbb', 'ccc', 'ooo']
------------------------------------------------------------------------------------------------------------------


insert() 

The insert() method inserts an element to the list at a given index.

The syntax of insert() method is
list.insert(index, element)

Example
list = ['aaa', 'bbb', 'ccc']

list.insert(1, "ooo")
print(list)

Output
['aaa', 'ooo', 'bbb', 'ccc']
-------------------------------------------------------------------------------------------------------------------

copy()

The copy() method returns a shallow copy of the list. It gives shallow copy that means modification in new list will not affect old list

The syntax of copy() method is:
new_list = list.copy()

Example
l = ['aaa', 'bbb', 'ccc', 'ooo']

x = l.copy()
print(l)

Output
['aaa', 'bbb', 'ccc', 'ooo']
-------------------------------------------------------------------------------------------------------------------------

extend()
The extend() method adds the specified list elements (or any iterable) to the end of the current list.

The syntax for extend() method
list.extend(seq)

Example
b1 = ['cse', 'ece', 'eee']
b2 = ['mec', 'civ', 'aero']
b1.extend(b2)
print(b1)

print(b2)

Output
['cse', 'ece', 'eee', 'mec', 'civ', 'aero']

['mec', 'civ', 'aero']
----------------------------------------------------------------------------------------------------------------------

count()
Python list method count() returns count of how many times obj occurs in list.

Syntax
The syntax for count() method
list.count(obj)

Example
L = [123, 'apple', 'banana', 'orange', 123];
print( "Count for 123 : ", L.count(123))
print ("Count for banana : ", L.count('banana'))

Output
Count for 123 :  2
Count for banana :  1
--------------------------------------------------------------------------------------------------------------------

remove()

The remove() method removes the first occurrence of the element with the specified value.

Syntax
list.remove(elmnt)

Example
b = ['cse', 'ece', 'eee']
b.remove("ece")
print(b)

Output
['cse', 'eee']
------------------------------------------------------------------------------------------------------------------

pop()

The pop() method removes the element at the specified position.

Syntax
list.pop(pos)

Example
languages = ['Python', 'Java', 'C++', 'Dotnet', 'C']
return_value = languages.pop(3)
print('Return Value:', return_value)
print('Updated List:', languages)


Output
Return Value: Dotnet
Updated List: ['Python', 'Java', 'C++', 'C']
----------------------------------------------------------------------------------------------------------------

reverse()
The reverse() method reverses the sorting order of the elements.

Syntax
list.reverse()

Example
b = ['cse', 'ece', 'eee','it','aero']
print('Original List:', b)
b.reverse()
print('Updated List:', b)

Output

Original List: ['cse', 'ece', 'eee', 'it', 'aero']
Updated List: ['aero', 'it', 'eee', 'ece', 'cse']
---------------------------------------------------------------------------------------------------------------

sort()

The sort() method sorts the elements of a given list in a specific order - Ascending.

The syntax of sort() method is:
list.sort(key=..., reverse=...)
Alternatively, you can also use Python's in-built function sorted() for the same purpose.
sorted(list, key=..., reverse=...)

Example
b = ['cse', 'ece', 'eee','it','aero']
b.sort()
print('Sorted List:', b)

Output

Sorted List: ['aero', 'cse', 'ece', 'eee', 'it']
----------------------------------------------------------------------------------------------------------------------- 

len() 

Python list function len() returns the number of elements in the list.

Syntax
The syntax for len() method
len(list)

Example
b = ['cse', 'ece', 'eee','it','aero']
c = ['red','green','blue']
print( "First list length : ", len(b))
print ("Second list length : ", len(c))

Output
First list length :  5
Second list length :  3
----------------------------------------------------------------------------------------------------------------------

Nested List
A list can contain any sort object, even another list (sublist), which in turn can contain sublists themselves, and so on. This is known as nested list. A nested list is created by placing a comma-separated sequence of sublists.

Example1
L = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']



Example2
b = ['cse', 'ece', ['eee','it',['aero','mech']],'civ','h&s']
print(b[2])   
print(b[2][2]) 
print(b[2][2][0])

Output
['eee', 'it', ['aero', 'mech']]
['aero', 'mech']
aero
-------------------------------------------------------------------------------------------------------------------------

List - Basic


List
A list is a collection which is ordered and changeable. In Python lists are written with square brackets.
Create a List:
list = ["aaa", "bbb", "ccc"]

Access Items with slicing
To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index.

my_list = ['p','r','o','g','r','a','m']
print(my_list[2:5])
print(my_list[:-5])
print(my_list[5:])
print(my_list[:])

Output

['o', 'g', 'r']
['p', 'r']
['a', 'm']
['p', 'r', 'o', 'g', 'r', 'a', 'm']



P
R
O
G
R
A
M
Positive index
0
1
2
3
4
5
6
Negative index
-7
-6
-5
-4
-3
-2
-1

Data types in Python


A data type represents the type of data stored into a variable or memory. The data types which are already available in Python language are called Built-in data types. The data types which can be created by the programmers are called User-defined data types. The built-in data types are of five types:
1.  None Type
2.  Numeric types
3.  Sequences
4.  Sets
5.  Mappings

      
     Python has five standard data types, named Numbers,  None, Sequences, Sets and Mappings.Python sets the  type of variable based on the type of value assigned to it  and it will automatically change the variable type if the  variable is set to some other value.

Numeric Types
 The numeric types represent numbers. There are three sub types:
·    int
·    float
·    complex 


Bool Data type
The bool data type in Python represents boolean values. There are only two boolean values True or False that can be represented by this data type. Python internally represents True as 1 and False as 0. A blank string like "" is also represented as False. Conditions will be evaluated internally to either True or False.

Sequences in Python
A sequence represents a group of elements or items. For example, a group of integer numbers will form a sequence. 

Mapping Types
 A map represents a group of elements in the form of key value pairs so that when the key is given, we can retrieve the value associated with it. The dict datatype is an example for a map. The ‘dict’ represents a ‘dictionary’ that contains pairs of elements such that the first element represents the key and the next one becomes its value. The key and its value should be separated by a colon (:) and every pair should be separated by a comma. All the elements should be enclosed inside curly brackets {}. We can create a dictionary by typing the roll numbers and names of students. Here, roll numbers are keys and names will become values. We write these key value pairs inside curly braces as:

d = {10: 'aaa', 11: 'bbb', 12: 'ccc', 13: 'ddd', 14: 'eee'}
Here, d is the name of the dictionary. 10 is the key and its associated value is ‘aaa’.

None Type
In Python, the ‘None’ data type represents an object that does not contain any value. In languages like Java, it is called ‘null’ object. But in Python, it is called ‘None’ object. In a Python program, maximum of only one ‘None’ object is provided. One of the uses of ‘None’ is that it is used inside a function as a default value of the arguments. When calling the function, if no value is passed, then the default value will be taken as ‘None’. If some value is passed to the function, then that value is used by the function. In Boolean expressions, ‘None’ data type represents ‘False’.

Friday, December 27, 2019

Introduction to Python

Python
Python is a programming language that combines the features of C and Java. It offers elegant style of developing programs like C. When the programmers want to go for object orientation, Python offers classes and objects like Java.

Python is open source software, which means anybody can freely download it from www.python.org and use it to develop programs. Its source code can be accessed and modified as required in the projects.
 Features of Python
There are various reasons why Python is gaining good popularity in the programming community. The following are some of the important features of Python:
1.      Simple: Python is a simple programming language. When we read a Python program, we feel like reading English sentences. It means more clarity and less stress on understanding the syntax of the language. Hence, developing and understanding programs will become easy.
2.      Easy to learn: Python uses very few keywords. Its programs use very simple structure. So, developing programs in Python become easy. Also, Python resembles C language. Most of the language constructs in C are also available in Python. Hence, migrating from C to Python is easy for programmers.
3.      Open source: There is no need to pay for Python software. Python can be freely downloaded from www.python.org website. Its source code can be read, modified and can be used in programs as desired by the programmers.
4.      High level language: Programming languages are of two types: low level and high level. A low level language uses machine code instructions to develop programs. These instructions directly interact with the CPU. Machine language and assembly language are called low level languages. High level languages use English words to develop programs. These are easy to learn and use. Like COBOL, PHP or Java, Python also uses English words in its programs and hence it is called high level programming language.
5.      Dynamically typed: In Python, we need not declare anything. An assignment statement binds a name to an object, and the object can be of any type. If a name is assigned to an object of one type, it may later be assigned to an object of a different type. This is the meaning of the saying that Python is a dynamically typed language. Languages like C and Java are statically typed. In these languages, the variable names and data types should be mentioned properly. Attempting to assign an object of the wrong type to a variable name triggers error or exception.
6.      Platform independent: When a Python program is compiled using a Python compiler, it generates byte code. Python’s byte code represents a fixed set of instructions that run on all operating systems and hardware. Using a Python Virtual Machine (PVM), anybody can run these byte code instructions on any computer system. Hence, Python programs are not dependent on any specific operating system. We can use Python on almost all operating systems like UNIX, Linux, Windows,Macintosh, Solaris, OS/2, Amiga, AROS, AS/400, etc. This makes Python an ideal programming language for any network or Internet.
7.      Portable: When a program yields the same result on any computer in the world, then it is called a portable program. Python programs will give the same result since they are platform independent. Once a Python program is written, it can run on any computer system using PVM. However, Python also contains some system dependent modules (or code), which are specific to operating system. Programmers should be careful about such code while developing the software if they want it to be completely portable.
8.  Procedure and object oriented: Python is a procedure oriented as well as an object oriented programming language. In procedure oriented programming languages (e.g. C and Pascal), the programs are built using functions and procedures. But in object oriented languages (e.g. C++ and Java), the programs use classes and objects.