id
int64
0
25.6k
text
stringlengths
0
4.59k
10,900
venture of iit bombay vjti alumni this produce the following result ['abcd' 'john' abcd [ [ 'john' [ 'john' 'john'['abcd' 'john' 'john'python tuples tuple is another sequence data type that is similar to the list tuple consists of number of values separated by commas unlike listshowevertuples are enclosed within parentheses the main differences between lists and tuples arelists are enclosed in brackets and their elements and size can be changedwhile tuples are enclosed in parentheses and cannot be updated tuples can be thought of as readonly lists for example #!/usr/bin/python tuple 'abcd' 'john'
10,901
venture of iit bombay vjti alumni tinytuple ( 'john'print tuple prints complete list print tuple[ prints first element of the list print tuple[ : prints elements starting from nd till rd print tuple[ :prints elements starting from rd element print tinytuple prints list two times print tuple tinytuple prints concatenated lists this produce the following result ('abcd' 'john' abcd ( ( 'john' ( 'john' 'john'('abcd' 'john' 'john'
10,902
venture of iit bombay vjti alumni the following code is invalid with tuplebecause we attempted to update tuplewhich is not allowed similar case is possible with lists #!/usr/bin/python tuple 'abcd' 'john' list 'abcd' 'john' tuple[ invalid syntax with tuple list[ valid syntax with list python dictionary python' dictionaries are kind of hash table type they work like associative arrays or hashes found in perl and consist of key-value pairs dictionary key can be almost any python typebut are usually numbers or strings valueson the other handcan be any arbitrary python object dictionaries are enclosed by curly braces (}and values can be assigned and accessed using square braces ([]for example #!/usr/bin/python dict {
10,903
venture of iit bombay vjti alumni dict['one'"this is onedict[ "this is twotinydict {'name''john','code': 'dept''sales'print dict['one'prints value for 'onekey print dict[ prints value for key print tinydict prints complete dictionary print tinydict keys(prints all the keys print tinydict values(prints all the values this produce the following result this is one this is two {'dept''sales''code' 'name''john'['dept''code''name'['sales' 'john'dictionaries have no concept of order among elements it is incorrect to say that the elements are "out of order"they are simply unordered
10,904
venture of iit bombay vjti alumni data type conversion sometimesyou may need to perform conversions between the built-in types to convert between typesyou simply use the type name as function there are several built-in functions to perform conversion from one data type to another these functions return new object representing the converted value sr no function description int( [,base]converts to an integer base specifies the base if is string long( [,baseconverts to long integer base specifies the base if is string float(xconverts to floating-point number complex(real [,imag]
10,905
venture of iit bombay vjti alumni creates complex number str(xconverts object to string representation repr(xconverts object to an expression string eval(strevaluates string and returns an object tuple(sconverts to tuple list(sconverts to list set(
10,906
venture of iit bombay vjti alumni converts to set dict(dcreates dictionary must be sequence of (key,valuetuples frozenset(sconverts to frozen set chr(xconverts an integer to character unichr(xconverts an integer to unicode character ord(xconverts single character to its integer value
10,907
venture of iit bombay vjti alumni hex(xconverts an integer to hexadecimal string oct(xconverts an integer to an octal string
10,908
venture of iit bombay vjti alumni python basic operators operators are the constructs which can manipulate the value of operands consider the expression here and are called operands and is called operator types of operator python language supports the following types of operators arithmetic operators comparison (relationaloperators assignment operators logical operators bitwise operators membership operators identity operators let us have look on all operators one by one
10,909
venture of iit bombay vjti alumni python arithmetic operators assume variable holds and variable holds then show example operator description example addition adds values on either side of the operator subtraction subtracts right hand operand from left hand operand multiplies values on either side of the operator multiplication division divides left hand operand by right hand / =
10,910
venture of iit bombay vjti alumni operand modulus *exponent divides left hand operand by right hand operand and returns remainder performs exponential (powercalculation on ** operators = to the power /floor division the division of operands where // the result is the quotient in which the digits and after the decimal point are removed but if one // of the operands is negativethe result is flooredi rounded away from zero (towards // negative infinity- // - python comparison operators
10,911
venture of iit bombay vjti alumni these operators compare the values on either sides of them and decide the relation among them they are also called relational operators assume variable holds and variable holds then show example operator description example =if the values of two operands are equalthen the ( =bcondition becomes true is not true !if values of two operands are not equalthen ( !bcondition becomes true is true if values of two operands are not equalthen ( bcondition becomes true is this true is similar to !
10,912
venture of iit bombay vjti alumni operator ><if the value of left operand is greater than the ( bvalue of right operandthen condition becomes is true true if the value of left operand is less than the value of ( bright operandthen condition becomes true is true if the value of left operand is greater than or equal ( >bto the value of right operandthen condition is becomes true true if the value of left operand is less than or equal to ( <bthe value of right operandthen condition becomes is true true python assignment operators not not
10,913
venture of iit bombay vjti alumni assume variable holds and variable holds then show example operator description example assigns values from right side operands to left side operand assigns value of into +add and it adds right operand to the left operand and + is assign the result to left operand equivalent to -it subtracts right operand from the left operand - is subtract and assign the result to left operand equivalent and to
10,914
venture of iit bombay vjti alumni *it multiplies right operand with the left operand * is multiply and assign the result to left operand equivalent and to /divide it divides left operand with the right operand / is and and assign the result to left operand equivalent to ac / is equivalent to %it takes modulus using two operands and assign % is modulus the result to left operand equivalent and to % **performs exponential (powercalculation on ** is
10,915
venture of iit bombay vjti alumni exponent operators and assign value to the left operand and equivalent to * //floor it performs floor division on operators and // is division assign value to the left operand equivalent to / python bitwise operators bitwise operator works on bits and performs bit by bit operation assume if and now in binary format they will be as follows & |
10,916
venture of iit bombay vjti alumni ^ ~ there are following bitwise operators supported by python language operator description example operator copies bit to the result if it exists ( in both operands (means binary and binary or it copies bit if it exists in either operand ( (means binary xor it copies the bit if it is set in one operand ( bbut not both (means binary it is unary and has the effect of 'flipping(~ -
10,917
venture of iit bombay vjti alumni ones bits (means complement in ' complement form due to signed binary number <binary left shift >binary right shift the left operands value is moved left by the < number (means of bits specified by the right operand the left operands value is moved right by > the number of bits specified by the right operand (means python logical operators there are following logical operators supported by python language assume variable holds and variable holds then
10,918
venture of iit bombay vjti alumni used to reverse the logical state of its operand python membership operators python' membership operators test for membership in sequencesuch as stringslistsor tuples there are two membership operators as explained below operator description example in evaluates to true if it finds variable in the in yspecified sequence and false otherwise here in results in if is member of sequence not in evaluates to true if it does not finds variable in not in yhere
10,919
venture of iit bombay vjti alumni the specified sequence and false otherwise not in results in if is not member of sequence python identity operators identity operators compare the memory locations of two objects there are two identity operators explained below operator description is evaluates to true if the variables on either side of the operator point to the same object and false otherwise example is yhere is results in if id(
10,920
venture of iit bombay vjti alumni equals id(yis not evaluates to false if the variables on either side of is not ythe operator point to the same object and true here is otherwise not results in if id(xis not equal to id(ypython operators precedence the following table lists all operators from highest precedence to lowest sr no operator description *exponentiation (raise to the power ~+
10,921
venture of iit bombay vjti alumni complementunary plus and minus (method names for the last two are +and -@ /multiplydividemodulo and floor division +addition and subtraction ><right and left bitwise shift bitwise 'and ^bitwise exclusive `orand regular `or
10,922
venture of iit bombay vjti alumni >comparison operators =!equality operators %///-+***assignment operators is is not identity operators in not in membership operators not or and logical operators
10,923
venture of iit bombay vjti alumni python decision making decision making is anticipation of conditions occurring while execution of the program and specifying actions taken according to the conditions decision structures evaluate multiple expressions which produce true or false as outcome you need to determine which action to take and which statements to execute if outcome is true or false otherwise following is the general form of typical decision making structure found in most of the programming languages
10,924
venture of iit bombay vjti alumni python programming language assumes any non-zero and non-null values as trueand if it is either zero or nullthen it is assumed as false value python programming language provides following types of decision making statements click the following links to check their detail sr no statement description if statements an if statement consists of boolean expression followed by one or more statements if else statements an if statement can be followed by an optional else statementwhich executes when the boolean expression is false nested if statements you can use one if or else if statement inside
10,925
venture of iit bombay vjti alumni another if or else ifstatement(slet us go through each decision making briefly single statement suites if the suite of an if clause consists only of single lineit may go on the same line as the header statement here is an example of one-line if clause #!/usr/bin/python var if var = print "value of expression is print "good bye!when the above code is executedit produces the following result value of expression is good bye
10,926
venture of iit bombay vjti alumni python loops in generalstatements are executed sequentiallythe first statement in function is executed firstfollowed by the secondand so on there may be situation when you need to execute block of code several number of times programming languages provide various control structures that allow for more complicated execution paths loop statement allows us to execute statement or group of statements multiple times the following diagram illustrates loop statement
10,927
venture of iit bombay vjti alumni python programming language provides following types of loops to handle looping requirements sr no loop type description while loop repeats statement or group of statements while given condition is true it tests the condition before executing the loop body for loop executes sequence of statements multiple times and abbreviates the code that manages the loop variable nested loops you can use one or more loop inside any another whilefor or do while loop
10,928
venture of iit bombay vjti alumni loop control statements loop control statements change execution from its normal sequence when execution leaves scopeall automatic objects that were created in that scope are destroyed python supports the following control statements click the following links to check their detail sr no control statement description break statement terminates the loop statement and transfers execution to the statement immediately following the loop continue statement causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating pass statement
10,929
venture of iit bombay vjti alumni the pass statement in python is used when statement is required syntactically but you do not want any command or code to execute
10,930
venture of iit bombay vjti alumni python numbers number data types store numeric values they are immutable data typesmeans that changing the value of number data type results in newly allocated object number objects are created when you assign value to them for example var var you can also delete the reference to number object by using the del statement the syntax of the del statement is del var [,var [,var ,varn]]]you can delete single object or multiple objects by using the del statement for example del var del var_avar_b python supports four different numerical types int (signed integersthey are often called just integers or intsare positive or negative whole numbers with no decimal point
10,931
venture of iit bombay vjti alumni long (long integers also called longsthey are integers of unlimited sizewritten like integers and followed by an uppercase or lowercase float (floating point real valuesalso called floatsthey represent real numbers and are written with decimal point dividing the integer and fractional parts floats may also be in scientific notationwith or indicating the power of ( complex (complex numbersare of the form bjwhere and are floats and (or jrepresents the square root of - (which is an imaginary numberthe real part of the number is aand the imaginary part is complex numbers are not used much in python programming examples here are some examples of numbers int long float complex -
10,932
venture of iit bombay vjti alumni - - - xdefabcecbdaecbfbael + - - + - - - + - - - python allows you to use lowercase with longbut it is recommended that you use only an uppercase to avoid confusion with the number python displays long integers with an uppercase complex number consists of an ordered pair of real floating point numbers denoted by bjwhere is the real part and is the imaginary part of the complex number
10,933
venture of iit bombay vjti alumni number type conversion python converts numbers internally in an expression containing mixed types to common type for evaluation but sometimesyou need to coerce number explicitly from one type to another to satisfy the requirements of an operator or function parameter type int(xto convert to plain integer type long(xto convert to long integer type float(xto convert to floating-point number type complex(xto convert to complex number with real part and imaginary part zero type complex(xyto convert and to complex number with real part and imaginary part and are numeric expressions mathematical functions python includes following functions that perform mathematical calculations sr no function returns description abs(
10,934
venture of iit bombay vjti alumni the absolute value of xthe (positivedistance between and zero ceil(xthe ceiling of xthe smallest integer not less than cmp(xy- if exp(xthe exponential of xex fabs(xthe absolute value of floor(xthe floor of xthe largest integer not greater than
10,935
venture of iit bombay vjti alumni log(xthe natural logarithm of xfor log (xthe base- logarithm of for max( the largest of its argumentsthe value closest to positive infinity min( the smallest of its argumentsthe value closest to negative infinity modf(xthe fractional and integer parts of in two-item tuple both parts have the same sign as the integer part is returned as float pow(xy
10,936
venture of iit bombay vjti alumni the value of ** round( [, ] rounded to digits from the decimal point python rounds away from zero as tie-breakerround( is and round(- is - sqrt(xthe square root of for random number functions random numbers are used for gamessimulationstestingsecurityand privacy applications python includes following functions that are commonly used sr no function description choice(seqa random item from listtupleor string
10,937
venture of iit bombay vjti alumni randrange ([start,stop [,step] randomly selected element from range(startstopstep random( random float rsuch that is less than or equal to and is less than seed([ ]sets the integer starting value used in generating random numbers call this function before calling any other random module function returns none shuffle(lstrandomizes the items of list in place returns none uniform(xya random float rsuch that is less than or equal to and is less than
10,938
venture of iit bombay vjti alumni trigonometric functions python includes following functions that perform trigonometric calculations sr no function description acos(xreturn the arc cosine of xin radians asin(xreturn the arc sine of xin radians atan(xreturn the arc tangent of xin radians atan (yxreturn atan( )in radians
10,939
venture of iit bombay vjti alumni cos(xreturn the cosine of radians hypot(xyreturn the euclidean normsqrt( * * sin(xreturn the sine of radians tan(xreturn the tangent of radians degrees(xconverts angle from radians to degrees radians(xconverts angle from degrees to radians
10,940
venture of iit bombay vjti alumni mathematical constants the module also defines two mathematical constants sr no constants description pi the mathematical constant pi the mathematical constant
10,941
venture of iit bombay vjti alumni python strings strings are amongst the most popular types in python we can create them simply by enclosing characters in quotes python treats single quotes the same as double quotes creating strings is as simple as assigning value to variable for example var 'hello world!var "python programmingaccessing values in strings python does not support character typethese are treated as strings of length onethus also considered substring to access substringsuse the square brackets for slicing along with the index or indices to obtain your substring for example #!/usr/bin/python var 'hello world!var "python programming
10,942
venture of iit bombay vjti alumni print "var [ ]"var [ print "var [ : ]"var [ : when the above code is executedit produces the following result var [ ] var [ : ]ytho updating strings you can "updatean existing string by (re)assigning variable to another string the new value can be related to its previous value or to completely different string altogether for example #!/usr/bin/python var 'hello world!print "updated string :"var [: 'pythonwhen the above code is executedit produces the following result updated string :hello python
10,943
venture of iit bombay vjti alumni escape characters following table is list of escape or non-printable characters that can be represented with backslash notation an escape character gets interpretedin single quoted as well as double quoted strings backslash hexadecimal description notation character \ bell or alert \ backspace \cx control- \ - control-
10,944
venture of iit bombay vjti alumni \ escape \ formfeed \ -\ - \ meta-control- \nnn newline octal notationwhere is in the range \ carriage return \ space \ tab
10,945
venture of iit bombay vjti alumni \ vertical tab \ character \xnn hexadecimal notationwhere is in the range for string special operators assume string variable holds 'helloand variable holds 'python'then operator description example concatenation adds values on either side of will the operator give hellopython repetition creates new stringsconcatenating * will give
10,946
venture of iit bombay vjti alumni [multiple copies of the same string hellohello slice gives the character from the given index [ will give [:in not in / range slice gives the characters from the [ : will given range give ell membership returns true if character exists in will in the given string give membership returns true if character does not in not exist in the given string will give raw string suppresses actual meaning of print '\nescape characters the syntax for raw strings is prints \ exactly the same as for normal strings with the and print exception of the raw string operatorthe letter '\ 'prints
10,947
venture of iit bombay vjti alumni " ,which precedes the quotation marks the " \ can be lowercase (ror uppercase (rand must be placed immediately preceding the first quote mark format performs string formatting see at next section string formatting operator one of python' coolest features is the string format operator this operator is unique to strings and makes up for the pack of having functions from ' printf(family following is simple example #!/usr/bin/python print "my name is % and weight is % kg!('zara' when the above code is executedit produces the following result my name is zara and weight is kg
10,948
venture of iit bombay vjti alumni here is the list of complete set of symbols which can be used along with format conversion symbol % character % string conversion via str(prior to formatting % signed decimal integer % signed decimal integer % unsigned decimal integer
10,949
venture of iit bombay vjti alumni % octal integer % hexadecimal integer (lowercase letters% hexadecimal integer (uppercase letters% exponential notation (with lowercase ' '% exponential notation (with uppercase ' '% floating point real number % the shorter of % and % % the shorter of % and % other supported symbols and functionality are listed in the following table
10,950
venture of iit bombay vjti alumni symbol functionality argument specifies width or precision left justification display the sign leave blank space before positive number add the octal leading zero ' or hexadecimal leading ' xor ' 'depending on whether 'xor 'xwere used pad from left with zeros (instead of spaces'%%leaves you with single literal '%
10,951
venture of iit bombay vjti alumni (varmapping variable (dictionary argumentsm is the minimum total width and is the number of digits to display after the decimal point (if appl triple quotes python' triple quotes comes to the rescue by allowing strings to span multiple linesincluding verbatim newlinestabsand any other special characters the syntax for triple quotes consists of three consecutive single or double quotes #!/usr/bin/python para_str """this is long string that is made up of several lines and non-printable characters such as tab \ and they will show up that way when displayed newlines within the stringwhether explicitly given like
10,952
venture of iit bombay vjti alumni this within the brackets \ ]or just newline within the variable assignment will also show up ""print para_str when the above code is executedit produces the following result note how every single special character has been converted to its printed formright down to the last newline at the end of the string between the "up and closing triple quotes also note that newlines occur either with an explicit carriage return at the end of line or its escape code (\nthis is long string that is made up of several lines and non-printable characters such as tab and they will show up that way when displayed newlines within the stringwhether explicitly given like this within the brackets ]or just newline within the variable assignment will also show up raw strings do not treat the backslash as special character at all every character you put into raw string stays the way you wrote it
10,953
venture of iit bombay vjti alumni #!/usr/bin/python print ' :\\nowherewhen the above code is executedit produces the following result :\nowhere now let' make use of raw string we would put expression in 'expression'as follows #!/usr/bin/python print ' :\\nowherewhen the above code is executedit produces the following result :\\nowhere unicode string normal strings in python are stored internally as -bit asciiwhile unicode strings are stored as -bit unicode this allows for more varied set of charactersincluding special characters from most languages in the world 'll restrict my treatment of unicode strings to the following
10,954
venture of iit bombay vjti alumni #!/usr/bin/python print 'helloworld!when the above code is executedit produces the following result helloworldas you can seeunicode strings use the prefix ujust as raw strings use the prefix built-in string methods python includes the following built-in methods to manipulate strings sr no methods with description capitalize(capitalizes first letter of string center(widthfillcharreturns space-padded string with the original string centered
10,955
venture of iit bombay vjti alumni to total of width columns count(strbeg ,end=len(string)counts how many times str occurs in string or in substring of string if starting index beg and ending index end are given decode(encoding='utf- ',errors='strict'decodes the string using the codec registered for encoding encoding defaults to the default string encoding encode(encoding='utf- ',errors='strict'returns encoded string version of stringon errordefault is to raise valueerror unless errors is given with 'ignoreor 'replace endswith(suffixbeg= end=len(string)determines if string or substring of string (if starting index beg and ending index end are givenends with suffixreturns true if
10,956
venture of iit bombay vjti alumni so and false otherwise expandtabs(tabsize= expands tabs in string to multiple spacesdefaults to spaces per tab if tabsize not provided find(strbeg= end=len(string)determine if str occurs in string or in substring of string if starting index beg and ending index end are given returns index if found and - otherwise index(strbeg= end=len(string)same as find()but raises an exception if str not found isalnum(returns true if string has at least character and all characters are alphanumeric and false otherwise
10,957
venture of iit bombay vjti alumni isalpha(returns true if string has at least character and all characters are alphabetic and false otherwise isdigit(returns true if string contains only digits and false otherwise islower(returns true if string has at least cased character and all cased characters are in lowercase and false otherwise isnumeric(returns true if unicode string contains only numeric characters and false otherwise isspace(returns true if string contains only whitespace characters and false otherwise
10,958
venture of iit bombay vjti alumni istitle(returns true if string is properly "titlecasedand false otherwise isupper(returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise join(seqmerges (concatenatesthe string representations of elements in sequence seq into stringwith separator string len(stringreturns the length of the string ljust(width[fillchar]returns space-padded string with the original string leftjustified to total of width columns
10,959
venture of iit bombay vjti alumni lower(converts all uppercase letters in string to lowercase lstrip(removes all leading whitespace in string maketrans(returns translation table to be used in translate function max(strreturns the max alphabetical character from the string str min(strreturns the min alphabetical character from the string str replace(oldnew [max]replaces all occurrences of old in string with new or at most max
10,960
venture of iit bombay vjti alumni occurrences if max given rfind(strbeg= ,end=len(string)same as find()but search backwards in string rindexstrbeg= end=len(string)same as index()but search backwards in string rjust(width,[fillchar]returns space-padded string with the original string rightjustified to total of width columns rstrip(removes all trailing whitespace of string split(str=""num=string count(str)splits string according to delimiter str (space if not providedand returns list of substringssplit into at most num substrings
10,961
venture of iit bombay vjti alumni if given splitlinesnum=string count('\ ')splits string at all (or numnewlines and returns list of each line with newlines removed startswith(strbeg= ,end=len(string)determines if string or substring of string (if starting index beg and ending index end are givenstarts with substring strreturns true if so and false otherwise strip([chars]performs both lstrip(and rstrip(on string swapcase(inverts case for all letters in string title(
10,962
venture of iit bombay vjti alumni returns "titlecasedversion of stringthat isall words begin with uppercase and the rest are lowercase translate(tabledeletechars=""translates string according to translation table str( chars)removing those in the del string upper(converts lowercase letters in string to uppercase zfill (widthreturns original string leftpadded with zeros to total of width charactersintended for numberszfill(retains any sign given (less one zero isdecimal(returns true if unicode string contains only decimal characters and false otherwise
10,963
venture of iit bombay vjti alumni python lists the most basic data structure in python is the sequence each element of sequence is assigned number its position or index the first index is zerothe second index is oneand so forth python has six built-in types of sequencesbut the most common ones are lists and tupleswhich we would see in this tutorial there are certain things you can do with all sequence types these operations include indexingslicingaddingmultiplyingand checking for membership in
10,964
venture of iit bombay vjti alumni additionpython has built-in functions for finding the length of sequence and for finding its largest and smallest elements python lists the list is most versatile data type available in python which can be written as list of comma-separated values (itemsbetween square brackets important thing about list is that items in list need not be of the same type creating list is as simple as putting different comma-separated values between square brackets for example list ['physics''chemistry' ]list [ ]list [" "" "" "" "similar to string indiceslist indices start at and lists can be slicedconcatenated and so on accessing values in lists to access values in listsuse the square brackets for slicing along with the index or indices to obtain value available at that index for example #!/usr/bin/python list ['physics''chemistry' ]
10,965
venture of iit bombay vjti alumni list [ ]print "list [ ]"list [ print "list [ : ]"list [ : when the above code is executedit produces the following result list [ ]physics list [ : ][ updating lists you can update single or multiple elements of lists by giving the slice on the lefthand side of the assignment operatorand you can add to elements in list with the append(method for example #!/usr/bin/python list ['physics''chemistry' ]print "value available at index print list[
10,966
venture of iit bombay vjti alumni list[ print "new value available at index print list[ note append(method is discussed in subsequent section when the above code is executedit produces the following result value available at index new value available at index delete list elements to remove list elementyou can use either the del statement if you know exactly which element(syou are deleting or the remove(method if you do not know for example #!/usr/bin/python list ['physics''chemistry' ]
10,967
venture of iit bombay vjti alumni print list del list [ ]print "after deleting value at index print list when the above code is executedit produces following result ['physics''chemistry' after deleting value at index ['physics''chemistry' note remove(method is discussed in subsequent section basic list operations lists respond to the and operators much like stringsthey mean concatenation and repetition here tooexcept that the result is new listnot string in factlists respond to all of the general sequence operations we used on strings in the prior python expression results description
10,968
venture of iit bombay vjti alumni len([ ] length [ [ [ concatenation ['hi!' ['hi!''hi!''hi!''hi!'repetition in [ true membership for in [ ]print iteration indexingslicingand matrixes because lists are sequencesindexing and slicing work the same way for lists as they do for strings assuming following input ['spam''spam''spam!'
10,969
venture of iit bombay vjti alumni python expression results description [ 'spam!offsets start at zero [- 'spamnegativecount from the right [ :['spam''spam!'slicing fetches sections built-in list functions methods python includes the following list functions sr no function with description cmp(list list
10,970
venture of iit bombay vjti alumni compares elements of both lists len(listgives the total length of the list max(listreturns item from the list with max value min(listreturns item from the list with min value list(seqconverts tuple into list python includes following list methods sr no methods with description
10,971
venture of iit bombay vjti alumni list append(objappends object obj to list list count(objreturns count of how many times obj occurs in list list extend(seqappends the contents of seq to list list index(objreturns the lowest index in list that obj appears list insert(indexobjinserts object obj into list at offset index list pop(obj=list[- ]removes and returns last object or obj from list
10,972
venture of iit bombay vjti alumni list remove(objremoves object obj from list list reverse(reverses objects of list in place list sort([func]sorts objects of listuse compare func if given python tuples tuple is sequence of immutable python objects tuples are sequencesjust like lists the differences between tuples and lists arethe tuples cannot be changed unlike lists and tuples use parentheseswhereas lists use square brackets
10,973
venture of iit bombay vjti alumni creating tuple is as simple as putting different comma-separated values optionally you can put these comma-separated values between parentheses also for example tup ('physics''chemistry' )tup ( )tup " "" "" "" "the empty tuple is written as two parentheses containing nothing tup ()to write tuple containing single value you have to include commaeven though there is only one value tup ( ,)like string indicestuple indices start at and they can be slicedconcatenatedand so on accessing values in tuples to access values in tupleuse the square brackets for slicing along with the index or indices to obtain value available at that index for example
10,974
venture of iit bombay vjti alumni #!/usr/bin/python tup ('physics''chemistry' )tup ( )print "tup [ ]"tup [ print "tup [ : ]"tup [ : when the above code is executedit produces the following result tup [ ]physics tup [ : ][ updating tuples tuples are immutable which means you cannot update or change the values of tuple elements you are able to take portions of existing tuples to create new tuples as the following example demonstrates #!/usr/bin/python
10,975
venture of iit bombay vjti alumni tup ( )tup ('abc''xyz')following action is not valid for tuples tup [ so let' create new tuple as follows tup tup tup print tup when the above code is executedit produces the following result ( 'abc''xyz'delete tuple elements removing individual tuple elements is not possible there isof coursenothing wrong with putting together another tuple with the undesired elements discarded to explicitly remove an entire tuplejust use the del statement for example #!/usr/bin/python
10,976
venture of iit bombay vjti alumni tup ('physics''chemistry' )print tup del tupprint "after deleting tup print tup this produces the following result note an exception raisedthis is because after del tup tuple does not exist any more ('physics''chemistry' after deleting tup traceback (most recent call last)file "test py"line in print tupnameerrorname 'tupis not defined basic tuples operations
10,977
venture of iit bombay vjti alumni tuples respond to the and operators much like stringsthey mean concatenation and repetition here tooexcept that the result is new tuplenot string in facttuples respond to all of the general sequence operations we used on strings in the prior python expression results description len(( ) length ( ( ( concatenation ('hi!', ('hi!''hi!''hi!''hi!'repetition in ( true membership for in ( )print iteration
10,978
venture of iit bombay vjti alumni indexingslicingand matrixes because tuples are sequencesindexing and slicing work the same way for tuples as they do for strings assuming following input ('spam''spam''spam!'python results description [ 'spam!offsets start at zero [- 'spamnegativecount from the expression right [ :no enclosing delimiters ['spam''spam!'slicing fetches sections
10,979
venture of iit bombay vjti alumni any set of multiple objectscomma-separatedwritten without identifying symbolsi brackets for listsparentheses for tuplesetc default to tuplesas indicated in these short examples #!/usr/bin/python print 'abc'- + 'xyzxy print "value of " , when the above code is executedit produces the following result abc - + ( + jxyz value of built-in tuple functions python includes the following tuple functions sr no function with description cmp(tuple tuple
10,980
venture of iit bombay vjti alumni compares elements of both tuples len(tuplegives the total length of the tuple max(tuplereturns item from the tuple with max value min(tuplereturns item from the tuple with min value tuple(seqconverts list into tuple python dictionary each key is separated from its value by colon (:)the items are separated by commasand the whole thing is enclosed in curly braces an empty dictionary without any items is written with just two curly braceslike this{
10,981
venture of iit bombay vjti alumni keys are unique within dictionary while values may not be the values of dictionary can be of any typebut the keys must be of an immutable data type such as stringsnumbersor tuples accessing values in dictionary to access dictionary elementsyou can use the familiar square brackets along with the key to obtain its value following is simple example #!/usr/bin/python dict {'name''zara''age' 'class''first'print "dict['name']"dict['name'print "dict['age']"dict['age'when the above code is executedit produces the following result dict['name']zara dict['age'] if we attempt to access data item with keywhich is not part of the dictionarywe get an error as follows #!/usr/bin/python
10,982
venture of iit bombay vjti alumni dict {'name''zara''age' 'class''first'print "dict['alice']"dict['alice'when the above code is executedit produces the following result dict['alice']traceback (most recent call last)file "test py"line in print "dict['alice']"dict['alice']keyerror'aliceupdating dictionary you can update dictionary by adding new entry or key-value pairmodifying an existing entryor deleting an existing entry as shown below in the simple example #!/usr/bin/python dict {'name''zara''age' 'class''first'dict['age' update existing entry dict['school'"dps school"add new entry
10,983
venture of iit bombay vjti alumni print "dict['age']"dict['age'print "dict['school']"dict['school'when the above code is executedit produces the following result dict['age'] dict['school']dps school delete dictionary elements you can either remove individual dictionary elements or clear the entire contents of dictionary you can also delete entire dictionary in single operation to explicitly remove an entire dictionaryjust use the del statement following is simple example #!/usr/bin/python dict {'name''zara''age' 'class''first'del dict['name']remove entry with key 'namedict clear()remove all entries in dict
10,984
venture of iit bombay vjti alumni del dict delete entire dictionary print "dict['age']"dict['age'print "dict['school']"dict['school'this produces the following result note that an exception is raised because after del dict dictionary does not exist any more dict['age']traceback (most recent call last)file "test py"line in print "dict['age']"dict['age']typeerror'typeobject is unsubscriptable note del(method is discussed in subsequent section properties of dictionary keys dictionary values have no restrictions they can be any arbitrary python objecteither standard objects or user-defined objects howeversame is not true for the keys there are two important points to remember about dictionary keys
10,985
venture of iit bombay vjti alumni (amore than one entry per key not allowed which means no duplicate key is allowed when duplicate keys encountered during assignmentthe last assignment wins for example #!/usr/bin/python dict {'name''zara''age' 'name''manni'print "dict['name']"dict['name'when the above code is executedit produces the following result dict['name']manni (bkeys must be immutable which means you can use stringsnumbers or tuples as dictionary keys but something like ['key'is not allowed following is simple example #!/usr/bin/python dict {['name']'zara''age'
10,986
venture of iit bombay vjti alumni print "dict['name']"dict['name'when the above code is executedit produces the following result traceback (most recent call last)file "test py"line in dict {['name']'zara''age' }typeerrorlist objects are unhashable built-in dictionary functions methods python includes the following dictionary functions sr no function with description cmp(dict dict compares elements of both dict len(dictgives the total length of the dictionary this would be equal to the number of items in the dictionary
10,987
venture of iit bombay vjti alumni str(dictproduces printable string representation of dictionary type(variablereturns the type of the passed variable if passed variable is dictionarythen it would return dictionary type python includes following dictionary methods sr no methods with description dict clear(removes all elements of dictionary dict dict copy(returns shallow copy of dictionary dict dict fromkeys(
10,988
venture of iit bombay vjti alumni create new dictionary with keys from seq and values set to value dict get(keydefault=nonefor key keyreturns value or default if key not in dictionary dict has_key(keyreturns true if key in dictionary dictfalse otherwise dict items(returns list of dict' (keyvaluetuple pairs dict keys(returns list of dictionary dict' keys dict setdefault(keydefault=nonesimilar to get()but will set dict[key]=default if key is not already in dict
10,989
venture of iit bombay vjti alumni dict update(dict adds dictionary dict ' key-values pairs to dict dict values(returns list of dictionary dict' values
10,990
venture of iit bombay vjti alumni python date time python program can handle date and time in several ways converting between date formats is common chore for computers python' time and calendar modules help track dates and times what is ticktime intervals are floating-point numbers in units of seconds particular instants in time are expressed in seconds since : amjanuary (epochthere is popular time module available in python which provides functions for working with timesand for converting between representations the function time time(returns the current system time in ticks since : amjanuary (epochexample #!/usr/bin/python import timethis is required to include time module ticks time time(
10,991
venture of iit bombay vjti alumni print "number of ticks since : amjanuary :"ticks this would produce result something as follows number of ticks since : amjanuary date arithmetic is easy to do with ticks howeverdates before the epoch cannot be represented in this form dates in the far future also cannot be represented this way the cutoff point is sometime in for unix and windows what is timetuplemany of python' time functions handle time as tuple of numbersas shown below index field values -digit year month to day to
10,992
venture of iit bombay vjti alumni hour to minute to second to ( or are leapseconds day of week to ( is monday day of year to (julian day daylight savings - - means library determines dst the above tuple is equivalent to struct_time structure this structure has following attributes
10,993
venture of iit bombay vjti alumni index attributes values tm_year tm_mon to tm_mday to tm_hour to tm_min to tm_sec to ( or are leapseconds tm_wday to ( is monday
10,994
venture of iit bombay vjti alumni tm_yday to (julian day tm_isdst - - means library determines dst getting current time to translate time instant from seconds since the epoch floating-point value into time-tuplepass the floating-point value to function ( localtimethat returns time-tuple with all nine items valid #!/usr/bin/python import timelocaltime time localtime(time time()print "local current time :"localtime this would produce the following resultwhich could be formatted in any other presentable form local current time time struct_time(tm_year= tm_mon=
10,995
venture of iit bombay vjti alumni tm_mday= tm_hour= tm_min= tm_sec= tm_wday= tm_yday= tm_isdst= getting formatted time you can format any time as per your requirementbut simple method to get time in readable format is asctime(#!/usr/bin/python import timelocaltime time asctimetime localtime(time time()print "local current time :"localtime this would produce the following result local current time tue jan : : getting calendar for month the calendar module gives wide range of methods to play with yearly and monthly calendars herewe print calendar for given month jan
10,996
venture of iit bombay vjti alumni #!/usr/bin/python import calendar cal calendar month( print "here is the calendar:print cal this would produce the following result here is the calendarjanuary mo tu we th fr sa su
10,997
venture of iit bombay vjti alumni the time module there is popular time module available in python which provides functions for working with times and for converting between representations here is the list of all available methods sr no function with description time altzone the offset of the local dst timezonein seconds west of utcif one is defined this is negative if the local dst timezone is east of utc (as in western europeincluding the ukonly use this if daylight is nonzero time asctime([tupletime]accepts time-tuple and returns readable -character string such as 'tue dec : : time clockreturns the current cpu time as floating-point number of seconds to measure computational costs of different
10,998
venture of iit bombay vjti alumni approachesthe value of time clock is more useful than that of time time( time ctime([secs]like asctime(localtime(secs)and without arguments is like asctime time gmtime([secs]accepts an instant expressed in seconds since the epoch and returns time-tuple with the utc time note tm_isdst is always time localtime([secs]accepts an instant expressed in seconds since the epoch and returns time-tuple with the local time ( tm_isdst is or depending on whether dst applies to instant secs by local rules time mktime(tupletimeaccepts an instant expressed as time-tuple in local time and
10,999
venture of iit bombay vjti alumni returns floating-point value with the instant expressed in seconds since the epoch time sleep(secssuspends the calling thread for secs seconds time strftime(fmt[,tupletime]accepts an instant expressed as time-tuple in local time and returns string representing the instant as specified by string fmt time strptime(str,fmt='% % % % :% :% % 'parses str according to format string fmt and returns the instant in time-tuple format time timereturns the current time instanta floating-point number of seconds since the epoch time tzset(