Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore Python Tutorial

Python Tutorial

Published by chetan.135, 2018-03-31 00:58:24

Description: Python Tutorial

Search

Read the Text Version

Dot Technologies Python If Else Statements The If statement is used to test specified condition and if the condition is true, if block executes, otherwise else block executes. The else statement executes when the if statement is false. Python If Else Syntaxif(condition): False statements else: True statements Example-year=2000if year%4==0: print \"Year is Leap\"else: print \"Year is not Leap\" 51

Dot TechnologiesOutput: Year is Leap Python Nested If Else Statement In python, we can use nested If Else to check multiple conditions. Python provides elif keyword to make nested If statement. This statement is like executing a if statement inside a else statement. Python Nested If Else SyntaxIf statement: Bodyelif statement: Bodyelse: Body Python Nested If Else Examplea=10if a>=20: print \"Condition is True\"else: if a>=15: print \"Checking second value\" else: print \"All Conditions are false\" Output: All Conditions are false. 52

Dot TechnologiesFor LoopPython for loop is used to iterate the elements of a collection in the order that theyappear. This collection can be a sequence(list or string).Python For Loop Syntaxfor <variable> in <sequence>:Output: 1 7 9Explanation: o Firstly, the first value will be assigned in the variable. o Secondly all the statements in the body of the loop are executed with the same value. o Thirdly, once step second is completed then variable is assigned the next value in the sequence and step second is repeated. o Finally, it continues till all the values in the sequence are assigned in the variable and processed.Python For Loop Simple Examplenum=2for a in range (1,6): print num * aOutput: 2 53

Dot Technologies 4 6 8 10Python Example to Find Sum of 10 Numberssum=0for n in range(1,11): sum+=nprint sumOutput:55Python Nested For LoopsLoops defined within another Loop are called Nested Loops. Nested loops are used toiterate matrix elements or to perform complex computation.When an outer loop contains an inner loop in its body it is called Nested Looping.Python Nested For Loop Syntaxfor <expression>: for <expression>: BodyPython Nested For Loop Examplefor i in range(1,6): for j in range (1,i+1): 54

print i, Dot Technologies print 55Output:>>>122333444455555>>>Explanation:For each value of Outer loop the whole inner loop is executed.For each value of inner loop the Body is executed each time.Python Nested Loop Example 2 for i in range (1,6): for j in range (5,i-1,-1): print \"*\", print Output: >>> ***** **** *** ** *

Dot TechnologiesPython While LoopIn Python, while loop is used to execute number of statements or body till the specifiedcondition is true. Once the condition is false, the control will come out of the loop.Python While Loop Syntaxwhile <expression>: BodyHere, loop Body will execute till the expression passed is true. The Body may be a singlestatement or multiple statement.Python While Loop Example 1a=10while a>0: print \"Value of a is\",a a=a-2print \"Loop is Completed\"Output:>>>Value of a is 10Value of a is 8Value of a is 6Value of a is 4Value of a is 2Loop is Completed>>>Explanation: 56

Dot Technologies o Firstly, the value in the variable is initialized. o Secondly, the condition/expression in the while is evaluated. Consequently if condition is true, the control enters in the body and executes all the statements . If the condition/expression passed results in false then the control exists the body and straight away control goes to next instruction after body of while. o Thirdly, in case condition was true having completed all the statements, the variable is incremented or decremented. Having changed the value of variable step second is followed. This process continues till the expression/condition becomes false. o Finally Rest of code after body is executed.Python While Loop Example 2n=153sum=0while n>0: r=n%10 sum+=r n=n/10print sumOutput:>>>9>>> 57

Dot TechnologiesPython BreakBreak statement is a jump statement which is used to transfer execution control. Itbreaks the current execution and in case of inner loop, inner loop terminatesimmediately.When break statement is applied the control points to the line following the body of theloop, hence applying break statement makes the loop to terminate and controls goes tonext line pointing after loop body.Python Break Example 1for i in [1,2,3,4,5]: if i==4: print \"Element found\" break print i,Output:>>>1 2 3 Element found>>>Python Break Example 2for letter in 'Python3': if letter == 'o': break print (letter)Output:Pyth 58

Dot TechnologiesPython Continue StatementPython Continue Statement is a jump statement which is used to skip execution ofcurrent iteration. After skipping, loop continue with next iteration.We can use continue statement with for as well as while loop in Python.Python Continue Statement Examplea=0while a<=5: a=a+1 if a%2==0: continue print aprint \"End of Loop\"Output:>>>135End of Loop>>> 59

Dot TechnologiesPython Continue Statement Flow chart 60

Dot TechnologiesPython PassIn Python, pass keyword is used to execute nothing; it means, when we don't want toexecute code, the pass can be used to execute empty. It is same as the name refers to.It just makes the control to pass by without executing any code. If we want to bypassany code pass statement can be used.Python Pass SyntaxpassPython Pass Examplefor i in [1,2,3,4,5]: if i==3: pass print \"Pass when value is\",i print i,Output:>>>1 2 Pass when value is 3345>>> 61

Dot TechnologiesProgramsPython Program to check if a Number is Positive, Negative or ZeroWe can use a Python program to distinguish that if a number is positive,negative or zero.Positive Numbers: A number is known as a positive number if it has a greater valuethan zero. i.e. 1, 2, 3, 4 etc.Negative Numbers: A number is known as a negative number if it has a lesser valuethan zero. i.e. -1, -2, -3, -4 etc.See this example:num = float(input(\"Enter a number: \"))if num > 0: print(\"{0} is a positive number\".format(num))elif num == 0: print(\"{0} is zero\".format(num))else: print(\"{0} is negative number\".format(num))Output: 62

Dot TechnologiesNote:In the above example, elif statement is used. The elif statement is used to checkmultiple expressions for TRUE and executes a block of code when one of the conditionsbecomes TRUE.It is always followed by if statement.Python Program to Check if a Number is Odd or EvenOdd and Even numbers: 63

Dot TechnologiesIf you divide a number by 2 and it gives a remainder of 0 then it is known as evennumber, otherwise an odd number.Even number examples: 2, 4, 6, 8, 10, etc.Odd number examples:1, 3, 5, 7, 9 etc.See this example:num = int(input(\"Enter a number: \"))if (num % 2) == 0: print(\"{0} is Even number\".format(num))else: print(\"{0} is Odd number\".format(num))Output:Python Program to Check Leap YearLeap Year: 64

Dot TechnologiesA year is called a leap year if it contains an additional day which makes the number ofthe days in that year is 366. This additional day is added in February which makes it 29days long.A leap year occurred once every 4 years.How to determine if a year is a leap year?You should follow the following steps to determine whether a year is a leap year or not.1. If a year is evenly divisible by 4 means having no remainder then go to next step. If it is not divisible by 4. It is not a leap year. For example: 1997 is not a leap year.2. If a year is divisible by 4, but not by 100. For example: 2012, it is a leap year. If a year is divisible by both 4 and 100, go to next step.3. If a year is divisible by 100, but not by 400. For example: 1900, then it is not a leap year. If a year is divisible by both, then it is a leap year. So 2000 is a leap year.See this example:year = int(input(\"Enter a year: \"))if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print(\"{0} is a leap year\".format(year)) else: print(\"{0} is not a leap year\".format(year)) else: print(\"{0} is a leap year\".format(year))else: print(\"{0} is not a leap year\".format(year))Output: 65

Dot TechnologiesPython Program to Check Prime NumberPrime numbers:A prime number is a natural number greater than 1 and having no positive divisor otherthan 1 and itself.For example: 3, 7, 11 etc are prime numbers.Composite number:Other natural numbers that are not prime numbers are called composite numbers.For example: 4, 6, 9 etc. are composite numbers.See this example:num = int(input(\"Enter a number: \"))if num > 1: for i in range(2,num): if (num % i) == 0: 66

Dot Technologies print(num,\"is not a prime number\") print(i,\"times\",num//i,\"is\",num) break else: print(num,\"is a prime number\")else: print(num,\"is not a prime number\")Output: 67

Dot TechnologiesPython Program to Print all Prime Numbers between an IntervalWe have already read the concept of prime numbers in the previous program. Here, weare going to print the prime numbers between given interval.See this example:#Take the input from the user:lower = int(input(\"Enter lower range: \"))upper = int(input(\"Enter upper range: \"))for num in range(lower,upper + 1): if num > 1: for i in range(2,num): if (num % i) == 0: break else: print(num)This example will show the prime numbers between 10 and 50.Output: 68

Dot TechnologiesPython Program to Find the Factorial of a NumberWhat is factorial?Factorial is a non-negative integer. It is the product of all positive integers less than orequal to that number for which you ask for factorial. It is denoted by exclamation sign(!).For example:1. 4! = 4x3x2x1 = 24The factorial value of 4 is 24.Note: The factorial value of 0 is 1 always. (Rule violation)See this example: 69

Dot Technologiesnum = int(input(\"Enter a number: \"))factorial = 1if num < 0: print(\"Sorry, factorial does not exist for negative numbers\")elif num == 0: print(\"The factorial of 0 is 1\")else: for i in range(1,num + 1): factorial = factorial*i print(\"The factorial of\",num,\"is\",factorial)The following example displays the factorial of 5 and -5.Output: 70

Dot TechnologiesPython Program to Display the multiplication TableIn Python, you can make a program to display the multiplication table of any number.The following program displays the multiplication table (from 1 to 10) according to theuser input.See this example:num = int(input(\"Show the multiplication table of? \"))# using for loop to iterate multiplication 10 timesfor i in range(1,11): print(num,'x',i,'=',num*i)The following example shows the multiplication table of 18.Output:Python Program to Print the Fibonacci sequenceFibonacci sequence: 71

Dot TechnologiesThe Fibonacci sequence specifies a series of numbers where the next number is foundby adding up the two numbers just before it.For example:0, 1, 1, 2, 3, 5, 8, 13, 21, 34, and so on....See this example:nterms = int(input(\"How many terms you want? \"))# first two termsn1 = 0n2 = 1count = 2# check if the number of terms is validif nterms <= 0: print(\"Plese enter a positive integer\")elif nterms == 1: print(\"Fibonacci sequence:\") print(n1)else: print(\"Fibonacci sequence:\") print(n1,\",\",n2,end=', ') while count < nterms: nth = n1 + n2 print(nth,end=' , ') # update values n1 = n2 n2 = nth count += 1Output: 72

Dot TechnologiesPython Program to Check Armstrong NumberArmstrong number:A number is called Armstrong number if it is equal to the sum of the cubes of its owndigits.For example: 153 is an Armstrong number since 153 = 1*1*1 + 5*5*5 + 3*3*3.The Armstrong number is also known as narcissistic number.See this example: num = int(input(\"Enter a number: \"))sum = 0temp = num 73

Dot Technologieswhile temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10if num == sum: print(num,\"is an Armstrong number\")else: print(num,\"is not an Armstrong number\")Output:Python Program to Find Armstrong Number between an IntervalWe have already read the concept of Armstrong numbers in the previous program. Here,we print the Armstrong numbers within a specific given interval.See this example: 74

Dot Technologieslower = int(input(\"Enter lower range: \"))upper = int(input(\"Enter upper range: \"))for num in range(lower,upper + 1): sum = 0 temp = num while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 if num == sum: print(num)This example shows all Armstrong numbers between 100 and 500.Output: 75

Dot TechnologiesPython Program to Find the Sum of Natural NumbersNatural numbers:As the name specifies, a natural number is the number that occurs commonly andobviously in the nature. It is a whole, non-negative number.Some mathematicians think that a natural number must contain 0 and some don'tbelieve this theory. So, a list of natural number can be defined as:N= {0, 1, 2, 3, 4, .... and so on}N= {1, 2, 3, 4, .... and so on}See this example:num = int(input(\"Enter a number: \"))if num < 0: print(\"Enter a positive number\")else: sum = 0 # use while loop to iterate un till zero while(num > 0): sum += num num -= 1 print(\"The sum is\",sum)This example shows the sum of the first 100 positive numbers (0-100)Output: 76

Dot Technologies 77

Dot Technologies PYTHON STRINGS Python string is a built-in type text sequence. It is used to handle textual data in python. Python Strings are immutable sequences of Unicode points. Creating Strings are simplest and easy to use in Python. We can simply create Python String by enclosing a text in single as well as double quotes. Python treat both single and double quotes statements same. Accessing Python Strings o In Python, Strings are stored as individual characters in a contiguous memory location. o The benefit of using String is that it can be accessed from both the directions (forward and backward). o Both forward as well as backward indexing are provided using Strings in Python. o Forward indexing starts with 0,1,2,3,.... o Backward indexing starts with -1,-2,-3,-4,.... Example1. str[0]='P'=str[-6] , str[1]='Y' = str[-5] , str[2] = 'T' = str[-4] , str[3] = 'H' = str[- 3]2. str[4] = 'O' = str[-2] , str[5] = 'N' = str[-1]. 78

Dot TechnologiesPython String ExampleHere, we are creating a simple program to retrieve String in reverse as well as normalform.name=\"Rajat\"length=len(name)i=0for n in range(-1,(-length-1),-1): print name[i],\"\t\",name[n] i+=1Output:>>>RtaajjaatR>>>Python Strings OperatorsTo perform operation on string, Python provides basically 3 types of Operators that aregiven below. 1. Basic Operators. 2. Membership Operators. 3. Relational Operators.Python String Basic OperatorsThere are two types of basic operators in String \"+\" and \"*\". 79

Dot TechnologiesString Concatenation Operator (+)The concatenation operator (+) concatenates two Strings and creates a new String.Python String Concatenation Example>>> \"ratan\" + \"jaiswal\"Output:'ratanjaiswal'>>>Expression Output'10' + '20' '1020'\"s\" + \"007\" 's007''abcd123' + 'xyz4' 'abcd123xyz4'NOTE: Both the operands passed for concatenation must be of same type, else it willshow an error.Eg:'abc' + 3>>>output:Traceback (most recent call last): 80

Dot Technologies File \"\", line 1, in 'abc' + 3TypeError: cannot concatenate 'str' and 'int' objects>>>Python String Replication Operator (*)Replication operator uses two parameters for operation, One is the integer value andthe other one is the String argument.The Replication operator is used to repeat a string number of times. The string will berepeated the number of times which is given by the integer value.Python String Replication Example>>> 5*\"Vimal\"Output:'VimalVimalVimalVimalVimal'Expression Output\"soono\"*2 'soonosoono'3*'1' '111''$'*5 '$$$$$'NOTE: We can use Replication operator in any way i.e., int * string or string * int. Boththe parameters passed cannot be of same type. 81

Dot TechnologiesPython String Membership OperatorsMembership Operators are already discussed in the Operators section. Let see withcontext of String.There are two types of Membership operators1) in:\"in\" operator returns true if a character or the entire substring is present in thespecified string, otherwise false.2) not in:\"not in\" operator returns true if a character or entire substring does not existin the specified string, otherwise false.Python String membership operator Example>>> str1=\"javatpoint\">>> str2='sssit'>>> str3=\"seomount\">>> str4='java'>>> st5=\"it\">>> str6=\"seo\">>> str4 in str1True>>> str5 in str2>>> st5 in str2True>>> str6 in str3True>>> str4 not in str1False>>> str1 not in str4True 82

Dot TechnologiesPython Relational OperatorsAll the comparison (relational) operators i.e., (<,><=,>=,==,!=,<>) are alsoapplicable for strings. The Strings are compared based on the ASCII value orUnicode(i.e., dictionary Order).Python Relational Operators Example>>> \"RAJAT\"==\"RAJAT\"True>>> \"afsha\">='Afsha'True>>> \"Z\"<>\"z\"TrueExplanation:The ASCII value of a is 97, b is 98, c is 99 and so on. The ASCII value of A is 65,B is66,C is 67 and so on. The comparison between strings are done on the basis on ASCIIvalue.Python String Slice NotationPython String slice can be defined as a substring which is the part of the string. Thereforefurther substring can be obtained from a string.There can be many forms to slice a string, as string can be accessed or indexed fromboth the direction and hence string can also be sliced from both the directions.Python String Slice Syntax<string_name>[startIndex:endIndex],<string_name>[:endIndex],<string_name>[startIndex:] 83

Dot TechnologiesPython String Slice Example 1>>> str=\"Nikhil\">>> str[0:6]'Nikhil'>>> str[0:3]'Nik'>>> str[2:5]'khi'>>> str[:6]'Nikhil'>>> str[3:]'hil'Note: startIndex in String slice is inclusive whereas endIndex is exclusive.String slice can also be used with Concatenation operator to get whole string.Python String Slice Example 2>>> str=\"Mahesh\">>> str[:6]+str[6:]'Mahesh'//here 6 is the length of the string.Python String Functions and MethodsPython provides various predefined or built-in string functions. They are as follows:capitalize() It capitalizes the first character of the String. 84

Dot Technologiescount(string,begin,end) It Counts number of times substring occurs in a String between begin and end index.endswith(suffix It returns a Boolean value if the string terminates,begin=0,end=n) with given suffix between begin and end.find(substring ,beginIndex, It returns the index value of the string whereendIndex) substring is found between begin index and end index.index(subsring, It throws an exception if string is not found andbeginIndex, endIndex) works same as find() method.isalnum() It returns True if characters in the string are alphanumeric i.e., alphabets or numbers and there is at least 1 character. Otherwise it returns False.isalpha() It returns True when all the characters are alphabets and there is at least one character, otherwise False.isdigit() It returns True if all the characters are digit and there is at least one character, otherwise False.islower() It returns True if the characters of a string are in lower case, otherwise False.isupper() It returns False if characters of a string are in Upper case, otherwise False. 85

Dot Technologiesisspace() It returns True if the characters of a string are whitespace, otherwise false.len(string) It returns the length of a string.lower() It converts all the characters of a string to Lower case.upper() It converts all the characters of a string to Upper Case.startswith(str It returns a Boolean value if the string starts with,begin=0,end=n) given str between begin and end.swapcase() It inverts case of all characters in a string.lstrip() It removes all leading whitespace of a string and can also be used to remove particular character from leading.rstrip() It removes all trailing whitespace of a string and can also be used to remove particular character from trailing. Python String capitalize() Method Example This method capitalizes the first character of the String.1. >>> 'abc'.capitalize() Output: 86

Dot Technologies'Abc'Python String count(string) Method ExampleThis method counts number of times substring occurs in a String between begin andend index.msg = \"welcome to sssit\";substr1 = \"o\";print msg.count(substr1, 4, 16)substr2 = \"t\";print msg.count(substr2)Output:>>>22>>>Python String endswith(string) Method ExampleThis method returns a Boolean value if the string terminates with given suffix betweenbegin and end.string1=\"Welcome to SSSIT\";substring1=\"SSSIT\";substring2=\"to\";substring3=\"of\";print string1.endswith(substring1);print string1.endswith(substring2,2,16);print string1.endswith(substring3,2,19);print string1.endswith(substring3);Output: 87

Dot Technologies>>>TrueFalseFalseFalse>>>Python String find(string) Method ExampleThis method returns the index value of the string where substring is found betweenbegin index and end index.str=\"Welcome to SSSIT\";substr1=\"come\";substr2=\"to\";print str.find(substr1);print str.find(substr2);print str.find(substr1,3,10);print str.find(substr2,19);Output:>>>383-1>>>Python String index() Method ExampleThis method returns the index value of the string where substring is found betweenbegin index and end index.str=\"Welcome to world of SSSIT\";substr1=\"come\"; 88

Dot Technologiessubstr2=\"of\";print str.index(substr1);print str.index(substr2);print str.index(substr1,3,10);print str.index(substr2,19);Output:>>>3173Traceback (most recent call last): File \"C:/Python27/fin.py\", line 7, in print str.index(substr2,19);ValueError: substring not found>>>Python String isalnum() Method ExampleThis method returns True if characters in the string are alphanumeric i.e., alphabets ornumbers and there is at least 1 character. Otherwise it returns False.str=\"Welcome to sssit\"; print str.isalnum();str1=\"Python47\";print str1.isalnum();Output:>>>FalseTrue>>> 89

Dot TechnologiesPython String isalpha() Method ExampleIt returns True when all the characters are alphabets and there is at least one character,otherwise False.string1=\"HelloPython\"; # Even space is not allowedprint string1.isalpha();string2=\"This is Python2.7.4\"print string2.isalpha();Output:>>>TrueFalse>>>Python String isdigit() Method ExampleThis method returns True if all the characters are digit and there is at least one character,otherwise False.string1=\"HelloPython\";print string1.isdigit();string2=\"98564738\"print string2.isdigit();Output:>>>FalseTrue>>>Python String islower() Method ExampleThis method returns True if the characters of a string are in lower case, otherwise False. 90

Dot Technologiesstring1=\"Hello Python\";print string1.islower();string2=\"welcome to \"print string2.islower();Output:>>>FalseTrue>>>Python String isupper() Method ExampleThis method returns False if characters of a string are in Upper case, otherwise False.string1=\"Hello Python\";print string1.isupper();string2=\"WELCOME TO\"print string2.isupper();Output:>>>FalseTrue>>>Python String isspace() Method ExampleThis method returns True if the characters of a string are whitespace, otherwise false.string1=\" \";print string1.isspace();string2=\"WELCOME TO WORLD OF PYT\"print string2.isspace(); 91

Output: Dot Technologies 92>>>TrueFalse>>>Python String len(string) Method ExampleThis method returns the length of a string.string1=\" \";print len(string1);string2=\"WELCOME TO SSSIT\"print len(string2);Output:>>>416>>>Python String lower() Method ExampleIt converts all the characters of a string to Lower case.string1=\"Hello Python\";print string1.lower();string2=\"WELCOME TO SSSIT\"print string2.lower();Output:>>>hello pythonwelcome to sssit

Dot Technologies>>>Python String upper() Method ExampleThis method converts all the characters of a string to upper case.string1=\"Hello Python\";print string1.upper();string2=\"welcome to SSSIT\"print string2.upper();Output:>>>HELLO PYTHONWELCOME TO SSSIT>>>Python String startswith(string) Method ExampleThis method returns a Boolean value if the string starts with given str between beginand end.string1=\"Hello Python\";print string1.startswith('Hello');string2=\"welcome to SSSIT\"print string2.startswith('come',3,7);Output:>>>TrueTrue>>>Python String swapcase() Method ExampleIt inverts case of all characters in a string. 93

Dot Technologiesstring1=\"Hello Python\";print string1.swapcase();string2=\"welcome to SSSIT\"print string2.swapcase();Output:>>>hELLO pYTHONWELCOME TO sssit>>>Python String lstrip() Method ExampleIt removes all leading whitespace of a string and can also be used to remove particularcharacter from leading.string1=\" Hello Python\";print string1.lstrip();string2=\"@@@@@@@@welcome to SSSIT\"print string2.lstrip('@');Output:>>>Hello Pythonwelcome to world to SSSIT>>>Python String rstrip() Method ExampleIt removes all trailing whitespace of a string and can also be used to remove particularcharacter from trailing.string1=\" Hello Python \";print string1.rstrip(); 94

Dot Technologiesstring2=\"@welcome to SSSIT!!!\"print string2.rstrip('!');Output:>>> Hello Python@welcome to SSSIT>>> 95

Dot TechnologiesPython ListPython list is a data structure which is used to store various types of data.In Python, lists are mutable i.e., Python will not create a new list if we modify an elementof the list.It works as a container that holds other objects in a given order. We can perform variousoperations like insertion and deletion on list.A list can be composed by storing a sequence of different type of values separated bycommas.Python list is enclosed between square([]) brackets and elements are stored in the indexbasis with starting index 0.Python List Exampledata1=[1,2,3,4];data2=['x','y','z'];data3=[12.5,11.6];data4=['raman','rahul'];data5=[];data6=['abhinav',10,56.4,'a'];A list can be created by putting the value inside the square bracket and separated bycomma.Python List Syntax<list_name>=[value1,value2,value3,...,valuen];Syntax to Access Python List<list_name>[index]Python allows us to access value from the list by various ways. 96

Dot Technologies Python Accessing List Elements Example data1=[1,2,3,4]; data2=['x','y','z']; print data1[0] print data1[0:2] print data2[-3:-1] print data1[0:] print data2[:2] Output: >>> >>> 1 [1, 2] ['x', 'y'] [1, 2, 3, 4] ['x', 'y'] >>> Elements in a Lists: Following are the pictorial representation of a list. We can see that it allows to access elements from both end (forward and backward).Data=[1,2,3,4,5]; 97

Dot Technologies1. Data[0]=1=Data[-5] , Data[1]=2=Data[-4] , Data[2]=3=Data[-3] ,2. =4=Data[-2] , Data[4]=5=Data[-1].Note: Internal Memory Organization:List do not store the elements directly at the index. In fact a reference is stored at eachindex which subsequently refers to the object stored somewhere in the memory. This isdue to the fact that some objects may be large enough than other objects and hencethey are stored at some other memory location.Python List OperationsApart from creating and accessing elements from the list, Python allows us to performvarious other operations on the list. Some common operations are given belowa) Adding Python ListsIn Python, lists can be added by using the concatenation operator(+) to join two lists.Add lists Example 1list1=[10,20] list2=[30,40] list3=list1+list2 print list3 98

Dot TechnologiesOutput:>>> [10, 20, 30, 40] >>>Note: '+'operator implies that both the operands passed must be list else error will beshown. Add lists Example 2 list1=[10,20] list1+30 print list1 Output: Traceback (most recent call last): File \"C:/Python27/lis.py\", line 2, in <module> list1+30 b) Python Replicating lists Replicating means repeating, It can be performed by using '*' operator by a specific number of time. Python list Replication Examplelist1=[10,20]print list1*1 Output: >>> [10, 20] >>> 99

Dot Technologiesc)Python List SlicingA subpart of a list can be retrieved on the basis of index. This subpart is known as listslice. This feature allows us to get sub-list of specified start and end index.Python List Slicing Examplelist1=[1,2,4,5,7]print list1[0:2]print list1[4]list1[1]=9print list1Output:>>>[1, 2]7[1, 9, 4, 5, 7]>>>Note: If the index provided in the list slice is outside the list, then it raises an IndexErrorexception.Python List Other OperationsApart from above operations various other functions can also be performed on List suchas Updating, Appending and Deleting elements from a List.Python Updating ListTo update or change the value of particular index of a list, assign the value to thatparticular index of the List. 100


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook