Answer stringlengths 0 5.21k | Question stringlengths 4 109 |
|---|---|
Its probably best to cite your favorite book about PythonThevery first articleabout Python was written in 1991 and is now quite outdatedGuido van Rossum and Jelke de Boer Interactively Testing Remote Servers Using the Python Programming Language CWI Quarterly Volume 4 Issue 4 December 1991 Amsterdam pp 283303 | Are there any published articles about python that i can reference? |
here are numerous tutorials and books available The standard documentation includesThe Python TutorialConsultthe Beginners Guideto find information for beginning Python programmers including lists of tutorials | I ve never programmed before is there a python tutorial? |
Alpha and beta releases are available fromhttpswwwpythonorgdownloads All releases are announced on the complangpython and complangpythonannounce newsgroups and on the Python home page athttpswwwpythonorg an RSS feed of news is availableYou can also access the development version of Python through Git SeeThe Python De... | How do i get a beta test version of python? |
In general no There are already millions of lines of Python code around the world so any change in the language that invalidates more than a very small fraction of existing programs has to be frowned upon Even if you can provide a conversion program theres still the problem of updating all documentation many books ha... | Is it reasonable to propose incompatible changes to python? |
Seehttpspepspythonorgfor the Python Enhancement Proposals PEPs PEPs are design documents describing a suggested new feature for Python providing a concise technical specification and a rationale Look for a PEP titled Python XY Release Schedule where XY is a version that hasnt been publicly released yetNew development ... | What new developments are expected for python in the future? |
e Python projects infrastructure is located all over the world and is managed by the Python Infrastructure Team Detailshere | Where in the world is www python org located? |
Python is an interpreted interactive objectoriented programming language It incorporates modules exceptions dynamic typing very high level dynamic data types and classes It supports multiple programming paradigms beyond objectoriented programming such as procedural and functional programming Python combines remarkabl... | What is python? |
Very stable New stable releases have been coming out roughly every 6 to 18 months since 1991 and this seems likely to continue As of version 39 Python will have a new feature release every 12 months PEP 602The developers issue bugfix releases of older versions so the stability of existing releases gradually improves ... | How stable is python? |
The latest Python source distribution is always available from pythonorg athttpswwwpythonorgdownloads The latest development sources can be obtained athttpsgithubcompythoncpythonThe source distribution is a gzipped tar file containing the complete C source Sphinxformatted documentation Python library modules example p... | How do i obtain a copy of the python source? |
Python is a highlevel generalpurpose programming language that can be applied to many different classes of problemsThe language comes with a large standard library that covers areas such as string processing regular expressions Unicode calculating differences between files internet protocols HTTP FTP SMTP XMLRPC POP IM... | What is python good for? |
o but it helps | Do i have to like monty python s flying circus? |
Yes there are many and more are being published See the pythonorg wiki athttpswikipythonorgmoinPythonBooksfor a listYou can also search online bookstores for Python and filter out the Monty Python references or perhaps search for Python and language | Are there any books on python? |
Seehttpswwwpythonorgaboutsuccessfor a list of projects that use Python Consulting the proceedings forpast Python conferenceswill reveal contributions from many different companies and organizationsHighprofile Python projects includethe Mailman mailing list managerandthe Zope application server Several Linux distributi... | Have any significant projects been done in python? |
You can do anything you want with the source as long as you leave the copyrights in and display those copyrights in any documentation about Python that you produce If you honor the copyright rules its OK to use Python for commercial use to sell copies of Python in source or binary form modified or unmodified or to sel... | Are there copyright restrictions on the use of python? |
YesIt is still common to start students with a procedural and statically typed language such as Pascal C or a subset of C or Java Students may be better served by learning Python as their first language Python has a very simple and consistent syntax and a large standard library and most importantly using Python in a ... | Is python a good language for beginning programmers? |
When he began implementing Python Guido van Rossum was also reading the published scripts fromMonty Pythons Flying Circus a BBC comedy series from the 1970s Van Rossum thought he needed a name that was short unique and slightly mysterious so he decided to call the language Python | Why is it called python? |
To report a bug or submit a patch use the issue tracker athttpsgithubcompythoncpythonissuesFor more information on how Python is developed consultthe Python Developers Guide | How do i submit bug reports and patches for python? |
Python versions are numbered ABC or ABAis the major version number it is only incremented for really major changes in the languageBis the minor version number it is incremented for less earthshattering changesCis the micro version number it is incremented for each bugfix releaseSeePEP 6for more information about bug... | How does the python version numbering scheme work? |
There are probably millions of users though its difficult to obtain an exact countPython is available for free download so there are no sales figures and its available from many different sites and packaged with many Linux distributions so download statistics dont tell the whole story eitherThe complangpython newsgroup... | How many people are using python? |
There is a newsgroupcomplangpython and a mailing listpythonlist The newsgroup and mailing list are gatewayed into each other if you can read news its unnecessary to subscribe to the mailing listcomplangpythonis hightraffic receiving hundreds of postings every day and Usenet readers are often more able to cope with th... | Is there a newsgroup or mailing list devoted to python? |
Heres averybrief summary of what started it all written by Guido van RossumI had extensive experience with implementing an interpreted language in the ABC group at CWI and from working with this group I had learned a lot about language design This is the origin of many Python features including the use of indentation ... | Why was python created in the first place? |
The Python Software Foundation is an independent nonprofit organization that holds the copyright on Python versions 21 and newer The PSFs mission is to advance open source technology related to the Python programming language and to publicize the use of Python The PSFs home page is athttpswwwpythonorgpsfDonations to ... | What is the python software foundation? |
The standard documentation for the current stable version of Python is available athttpsdocspythonorg3 PDF plain text and downloadable HTML versions are also available athttpsdocspythonorg3downloadhtmlThe documentation is written in reStructuredText and processed bythe Sphinx documentation tool The reStructuredText s... | How do i get documentation on python? |
Collect the arguments using theandspecifiers in the functions parameter list this gives you the positional arguments as a tuple and the keyword arguments as a dictionary You can then pass these arguments when calling another function by usinganddeffxargskwargskwargswidth143cgxargskwargs | How can i pass optional or keyword parameters from one function to another? |
To specify an octal digit precede the octal value with a zero and then a lower or uppercase o For example to set the variable a to the octal value 10 8 in decimal typea0o10a8Hexadecimal is just as easy Simply precede the hexadecimal number with a zero and then a lower or uppercase x Hexadecimal digits can be specifi... | How do i specify hexadecimal and octal integers? |
To convert eg the number144to the string144 use the builtin type constructorstr If you want a hexadecimal or octal representation use the builtin functionshexoroct For fancy formatting see thefstringsandFormat String Syntaxsections eg04dformat144yields0144and3fformat1030yields0333 | How do i convert a number to a string? |
ou can useSrstriprnto remove all occurrences of any line terminator from the end of the stringSwithout removing other trailing whitespace If the stringSrepresents more than one line with several empty lines at the end the line terminators for all the blank lines will be removedlinesline 1rnrnrnlinesrstripnrline 1 Sinc... | Is there an equivalent to perl s chomp for removing trailing newlines from strings? |
mma is not an operator in Python Consider this sessionainbaFalse aSince the comma is not an operator but a separator between expressions the above is evaluated as if you had enteredainbanotainbaThe same is true of the various assignment operators etc They are not truly operators but syntactic delimiters in assignment... | What s up with the comma operator s precedence? |
ou dont need the ability to compile Python to C code if all you want is a standalone program that users can download and run without having to install the Python distribution first There are a number of tools that determine the set of modules required by a program and bind these modules together with a Python binary t... | How can i create a stand alone binary from a python script? |
See the Python Cookbook for a long discussion of many ways to do thishttpscodeactivestatecomrecipes52560If you dont mind reordering the list sort it and then scan from the end of the list deleting duplicates as you goifmylistmylistsortlastmylist1foriinrangelenmylist211iflastmylistidelmylistielselastmylistiIf all elemen... | How do you remove duplicates from a list? |
The type constructortupleseqconverts any sequence actually any iterable into a tuple with the same items in the same orderFor exampletuple123yields123andtupleabcyieldsabc If the argument is a tuple it does not make a copy but returns the same object so it is cheap to calltuplewhen you arent sure that an object is alre... | How do i convert between tuples and lists? |
ariable names with double leading underscores are mangled to provide a simple but effective way to define class private variables Any identifier of the formspamat least two leading underscores at most one trailing underscore is textually replaced withclassnamespam whereclassnameis the current class name with any leadi... | I try to use spam and i get an error about someclassname spam? |
The two principal tools for caching methods arefunctoolscachedpropertyandfunctoolslrucache The former stores results at the instance level and the latter at the class levelThecachedpropertyapproach only works with methods that do not take any arguments It does not create a reference to the instance The cached method... | How do i cache method calls? |
For reasons of efficiency as well as consistency Python only reads the module file on the first time a module is imported If it didnt in a program consisting of many modules where each one imports the same basic module the basic module would be parsed and reparsed many times To force rereading of a changed module do ... | When i edit an imported module and reimport it the changes don t show up why does this happen? |
Use the builtin functionisinstanceobjcls You can check if an object is an instance of any of a number of classes by providing a tuple instead of a single class egisinstanceobjclass1class2 and can also check whether an object is one of Pythons builtin types egisinstanceobjstrorisinstanceobjintfloatcomplexNote thatisins... | How do i check if an object is an instance of a given class or of a subclass of it? |
How do I create a pyc fileWhen a module is imported for the first time or when the source file has changed since the current compiled file was created apycfile containing the compiled code should be created in apycachesubdirectory of the directory containing thepyfile Thepycfile will have a filename that starts with t... | Modules? |
eidbuiltin returns an integer that is guaranteed to be unique during the lifetime of the object Since in CPython this is the objects memory address it happens frequently that after an object is deleted from memory the next freshly created object is allocated at the same position in memory This is illustrated by this ... | Why does the result of id appear to be not unique? |
In Python variables that are only referenced inside a function are implicitly global If a variable is assigned a value anywhere within the functions body its assumed to be a local unless explicitly declared as globalThough a bit surprising at first a moments consideration explains this On one hand requiringglobalfor ... | What are the rules for local and global variables in python? |
The canonical way to share information across modules within a single program is to create a special module often called config or cfg Just import the config module in all modules of your application the module then becomes available as a global name Because there is only one instance of each module any changes made ... | How do i share global variables across modules? |
esSeveral debuggers for Python are described below and the builtin functionbreakpointallows you to drop into any of themThe pdb module is a simple but adequate consolemode debugger for Python It is part of the standard Python library and isdocumentedintheLibraryReferenceManual You can also write your own debugger by us... | Is there a source code level debugger with breakpoints single stepping etc? |
Delegation is an object oriented technique also called a design pattern Lets say you have an objectxand want to change the behaviour of just one of its methods You can create a new class that provides a new implementation of the method youre interested in changing and delegates all other methods to the corresponding m... | What is delegation? |
When subclassing an immutable type override thenewmethod instead of theinitmethod The latter only runsafteran instance is created which is too late to alter data in an immutable instanceAll of these immutable classes have a different signature than their parent classfromdatetimeimportdateclassFirstOfMonthDatedateAlway... | How can a subclass control what data is stored in an immutable instance? |
Use the builtinsuperfunctionclassDerivedBasedefmethselfsupermeth calls BasemethIn the examplesuperwill automatically determine the instance from which it was called theselfvalue look up themethod resolution orderMRO withtypeselfmro and return the next in line afterDerivedin the MROBase | How do i call a method defined in a base class from a derived class that extends it? |
Suppose you have the following modulesfoopyfrombarimportbarvarfoovar1barpyfromfooimportfoovarbarvar2The problem is that the interpreter will perform the following stepsmain importsfooEmpty globals forfooare createdfoois compiled and starts executingfooimportsbarEmpty globals forbarare createdbaris compiled and starts e... | How can i have modules that mutually import each other? |
A module can find out its own module name by looking at the predefined global variablename If this has the valuemain the program is running as a script Many modules that are usually used by importing them also provide a commandline interface or a selftest and only execute this code after checkingnamedefmainprintRunni... | How do i find the current module name? |
3Its primarily driven by the desire thatijhave the same sign asj If you want that and also wantiijjijthen integer division has to return the floor C also requires that identity to hold and then compilers that truncateijneed to makeijhave the same sign asiThere are few real use cases forijwhenjis negative Whenjis posi... | Why does 22 10 return 3? |
A raw string ending with an odd number of backslashes will escape the strings quoterCthiswillnotworkFilestdin line1rCthiswillnotworkSyntaxErrorunterminated string literal detected at line 1There are several workarounds for this One is to use regular strings and double the backslashesCthiswillworkCthiswillworkAnother is... | Can i end a raw string with an odd number of backslashes? |
There are several possible reasons for thisThedelstatement does not necessarily calldel it simply decrements the objects reference count and if this reaches zerodelis calledIf your data structures contain circular links eg a tree where each child has a parent reference and each parent has a list of children the referen... | My class defines del but it is not called when i delete the object? |
It can be a surprise to get theUnboundLocalErrorin previously working code when it is modified by adding an assignment statement somewhere in the body of a functionThis codex10defbarprintxbar10works but this codex10deffooprintxx1results in anUnboundLocalErrorfooTraceback most recent call lastUnboundLocalErrorlocal vari... | Why am i getting an unboundlocalerror when the variable has a value? |
If you wrote code likexyxyappend10y10x10you might be wondering why appending an element toychangedxtooThere are two factors that produce this resultVariables are simply names that refer to objects Doingyxdoesnt create a copy of the list it creates a new variableythat refers to the same objectxrefers to This means th... | Why did changing list y also change list x? |
Use thereversedbuiltin functionforxinreversedsequence do something with x This wont touch your original sequence but build a new copy with reversed order to iterate over | How do i iterate over a sequence in reverse order? |
When a module is imported for the first time or when the source file has changed since the current compiled file was created apycfile containing the compiled code should be created in apycachesubdirectory of the directory containing thepyfile Thepycfile will have a filename that starts with the same name as thepyfile ... | How do i create a pyc file? |
his is because of a combination of the fact that augmented assignment operators areassignmentoperators and the difference between mutable and immutable objects in PythonThis discussion applies in general when augmented assignment operators are applied to elements of a tuple that point to mutable objects but well use al... | Why does a tuple i item raise an exception when the addition works? |
sider using the convenience functionimportmodulefromimportlibinsteadzimportlibimportmodulexyz | Import x y z returns module x how do i get z? |
The technique attributed to Randal Schwartz of the Perl community sorts the elements of a list by a metric which maps each element to its sort value In Python use thekeyargument for thelistsortmethodIsortedLIsortedsortkeylambdasints1015 | I want to do a complicated sort can you do a schwartzian transform in python? |
Generally speaking it cant because objects dont really have names Essentially assignment always binds a name to a value the same is true ofdefandclassstatements but in that case the value is a callable Consider the following codeclassApassBAaBbaprintbmainA object at 0x16D07CCprintamainA object at 0x16D07CCArguably the ... | How can my code discover the name of an object? |
You have two choices you can use nested scopes or you can use callable objects For example suppose you wanted to definelinearabwhich returns a functionfxthat computes the valueaxb Using nested scopesdeflinearabdefresultxreturnaxbreturnresultOr using a callable objectclasslineardefinitselfabselfaselfbabdefcallselfxretu... | How do you make a higher order function in python? |
In general dont usefrommodulenameimport Doing so clutters the importers namespace and makes it much harder for linters to detect undefined namesImport modules at the top of a file Doing so makes it clear what other modules your code requires and avoids questions of whether the module name is in scope Using one import... | What are the best practices for using import in a module? |
For integers use the builtininttype constructor egint144144 Similarlyfloatconverts to floatingpoint egfloat1441440By default these interpret the number as decimal so thatint0144144holds true andint0x144raisesValueErrorintstringbasetakes the base to convert from as a second optional argument soint0x14416324 If the bas... | How do i convert a string to a number? |
This type of bug commonly bites neophyte programmers Consider this functiondeffoomydict Danger shared reference to one dict for all callscomputesomethingmydictkeyvaluereturnmydictThe first time you call this functionmydictcontains a single item The second timemydictcontains two items because whenfoobegins executingmy... | Why are default values shared between objects? |
Thats a tough one in general First here are a list of things to remember before diving furtherPerformance characteristics vary across Python implementations This FAQ focuses onCPythonBehaviour can vary across operating systems especially when talking about IO or multithreadingYou should always find the hot spots in y... | My program is too slow how do i speed it up? |
strandbytesobjects are immutable therefore concatenating many strings together is inefficient as each concatenation creates a new object In the general case the total runtime cost is quadratic in the total string lengthTo accumulate manystrobjects the recommended idiom is to place them into a list and callstrjoinat th... | What is the most efficient way to concatenate many strings together? |
As with removing duplicates explicitly iterating in reverse with a delete condition is one possibility However it is easier and faster to use slice replacement with an implicit or explicit forward iteration Here are three variationsmylistfilterkeepfunctionmylistmylistxforxinmylistifkeepconditionmylistxforxinmylistifke... | How do you remove multiple items from a list? |
A method is a function on some objectxthat you normally call asxnamearguments Methods are defined as functions inside the class definitionclassCdefmethselfargreturnarg2selfattribute | What is a method? |
es Usually this is done by nestinglambdawithinlambda See the following three examples slightly adapted from Ulf Barteltfromfunctoolsimportreduce Primes 1000printlistfilterNonemaplambdayyreducelambdaxyxy0maplambdaxyyyxrange2intpowy0511range21000 First 10 Fibonacci numbersprintlistmaplambdaxflambdaxffx1ffx2fifx1else1f... | Is it possible to write obfuscated one liners in python? |
A class is the particular object type created by executing a class statement Class objects are used as templates to create instance objects which embody both the data attributes and code methods specific to a datatypeA class can be based on one or more other classes called its base classes It then inherits the attribut... | What is a class? |
Merge them into an iterator of tuples sort the resulting list and then pick out the element you wantlist1whatImsortingbylist2somethingelsetosortpairsziplist1list2pairssortedpairspairsIm else by sort sorting to what somethingresultx1forxinpairsresultelse sort to something | How can i sort one list by values from another list? |
Yes there is The syntax is as followsontrueifexpressionelseonfalsexy5025smallxifxyelseyBefore this syntax was introduced in Python 25 a common idiom was to use logical operatorsexpressionandontrueoronfalseHowever this idiom is unsafe as it can give wrong results whenontruehas a false boolean value Therefore it is alwa... | Is there an equivalent of c s ternary operator? |
For an instancexof a userdefined classdirxreturns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class | How can i find the methods or attributes of an object? |
Use a listthis1isanarrayLists are equivalent to C or Pascal arrays in their time complexity the primary difference is that a Python list can contain objects of many different typesThearraymodule also provides methods for creating arrays of fixed types with compact representations but they are slower to index than lists... | How do you make an array in python? |
Remember that arguments are passed by assignment in Python Since assignment just creates references to objects theres no alias between an argument name in the caller and callee and so no callbyreference per se You can achieve the desired effect in a number of waysBy returning a tuple of the resultsdeffunc1abanewvalue... | How do i write a function with output parameters call by reference? |
Both static data and static methods in the sense of C or Java are supported in PythonFor static data simply define a class attribute To assign a new value to the attribute you have to explicitly use the class name in the assignmentclassCcount0 number of times Cinit calleddefinitselfCcountCcount1defgetcountselfreturnCc... | How do i create static class data and static class methods? |
In general trycopycopyorcopydeepcopyfor the general case Not all objects can be copied but most canSome objects can be copied more easily Dictionaries have acopymethodnewdictolddictcopySequences can be copied by slicingnewll | How do i copy an object in python? |
nSee theUnicode HOWTO | What does unicodedecodeerror or unicodeencodeerror error mean? |
ython sequences are indexed with positive numbers and negative numbers For positive numbers 0 is the first index 1 is the second index and so forth For negative indices 1 is the last index and 2 is the penultimate next to last index and so forth Think ofseqnas the same asseqlenseqnUsing negative indices can be very ... | What s a negative index? |
You could assign the base class to an alias and derive from the alias Then all you have to change is the value assigned to the alias Incidentally this trick is also handy if you want to decide dynamically eg depending on availability of resources which base class to use ExampleclassBaseBaseAliasBaseclassDerivedBaseA... | How can i organize my code to make it easier to change the base class? |
Yes The coding style required for standard library modules is documented asPEP 8 | Are there coding standards or a style guide for python programs? |
Python does not keep track of all instances of a class or of a builtin type You can program the classs constructor to keep track of all instances by keeping a list of weak references to each instance | How do i get a list of all instances of a given class? |
You probably tried to make a multidimensional array like thisANone23This looks correct if you print itANone None None None None NoneBut when you assign a value it shows up in multiple placesA005A5 None 5 None 5 NoneThe reason is that replicating a list withdoesnt create copies it only creates references to the existing... | How do i create a multidimensional list? |
This answer actually applies to all methods but the question usually comes up first in the context of constructorsIn C youd writeclassCCcoutNo argumentsnCinticoutArgument is inIn Python you have to write a single constructor that catches all cases using default arguments For exampleclassCdefinitselfiNoneifiisNoneprint... | How can i overload constructors or methods in python? |
Trying to lookup anintliteral attribute in the normal manner gives aSyntaxErrorbecause the period is seen as a decimal point1classFilestdin line11classSyntaxErrorinvalid decimal literalThe solution is to separate the literal from the period with either a space or parentheses1classclass int1classclass int | How do i get int literal attribute instead of syntaxerror? |
Not as suchFor simple input parsing the easiest approach is usually to split the line into whitespacedelimited words using thesplitmethod of string objects and then convert decimal strings to numeric values usingintorfloatsplitsupports an optional sep parameter which is useful if the line uses something other than whit... | Is there a scanf or sscanf equivalent? |
Assume you use a for loop to define a few different lambdas or even plain functions egsquaresforxinrange5squaresappendlambdax2This gives you a list that contains 5 lambdas that calculatex2 You might expect that when called they would return respectively0149 and16 However when you actually try you will see that they a... | Why do lambdas defined in a loop with different values all return the same result? |
To call a method or function and accumulate the return values is a list alist comprehensionis an elegant solutionresultobjmethodforobjinmylistresultfunctionobjforobjinmylistTo just run the method or function without saving the return values a plainforloop will sufficeforobjinmylistobjmethodforobjinmylistfunctionobj | How do i apply a method or function to a sequence of objects? |
A slash in the argument list of a function denotes that the parameters prior to it are positionalonly Positionalonly parameters are the ones without an externally usable name Upon calling a function that accepts positionalonly parameters arguments are mapped to parameters based solely on their position For examplediv... | What does the slash in the parameter list of a function mean? |
here are various techniquesThe best is to use a dictionary that maps strings to functions The primary advantage of this technique is that the strings do not need to match the names of the functions This is also the primary technique used to emulate a case constructdefapassdefbpassdispatchgoastopb Note lack of parens ... | How do i use strings to call functions methods? |
eisoperator tests for object identity The testaisbis equivalent toidaidbThe most important property of an identity test is that an object is always identical to itselfaisaalways returnsTrue Identity tests are usually faster than equality tests And unlike equality tests identity tests are guaranteed to return a boole... | When can i rely on identity tests with the is operator? |
Parametersare defined by the names that appear in a function definition whereasargumentsare the values actually passed to a function when calling it Parameters define whatkind of argumentsa function can accept For example given the function definitiondeffuncfoobarNonekwargspassfoobarandkwargsare parameters offunc Ho... | What is the difference between arguments and parameters? |
You cant because strings are immutable In most situations you should simply construct a new string from the various parts you want to assemble it from However if you need an object with the ability to modify inplace unicode data try using anioStringIOobject or thearraymoduleimportiosHello worldsioioStringIOssiogetval... | How do i modify a string in place? |
Self is merely a conventional name for the first argument of a method A method defined asmethselfabcshould be called asxmethabcfor some instancexof the class in which the definition occurs the called method will think it is called asmethxabcSee alsoWhy must self be used explicitly in method definitions and calls | What is self? |
YesPylintandPyflakesdo basic checking that will help you catch bugs soonerStatic type checkers such asMypyPyre andPytypecan check type hints in Python source code | Are there tools to help find bugs or perform static analysis? |
ython has awithstatement that wraps the execution of a block calling code on the entrance and exit from the block Some languages have a construct that looks like thiswithobja1 equivalent to obja 1totaltotal1 objtotal objtotal 1In Python such a construct would be ambiguousOther languages such as Object Pascal Delphi... | Why doesn t python have a with statement for attribute assignments? |
colon is required primarily to enhance readability one of the results of the experimental ABC language Consider thisifabprintaversusifabprintaNotice how the second one is slightly easier to read Notice further how a colon sets off the example in this FAQ answer its a standard usage in EnglishAnother minor reason is ... | Why are colons required for the if while def class statements? |
There are several advantagesOne is performance knowing that a string is immutable means we can allocate space for it at creation time and the storage requirements are fixed and unchanging This is also one of the reasons for the distinction between tuples and listsAnother advantage is that strings in Python are conside... | Why are python strings immutable? |
See the next question | Why am i getting strange results with simple arithmetic operations? |
Python lets you add a trailing comma at the end of lists tuples and dictionaries123abcdA15B67 last trailing comma is optional but good styleThere are several reasons to allow thisWhen you have a literal value for a list tuple or dictionary spread across multiple lines its easier to add more elements because you dont ha... | Why does python allow commas at the end of lists and tuples? |
or one thing this is not a C standard feature and hence its not portable Yes we know about the Boehm GC library It has bits of assembler code formostcommon platforms not for all of them and although it is mostly transparent it isnt completely transparent patches are required to get Python to work with itTraditional GC... | Why doesn t cpython use a more traditional garbage collection scheme? |
ython lambda expressions cannot contain statements because Pythons syntactic framework cant handle statements nested inside expressions However in Python this is not a serious problem Unlike lambda forms in other languages where they add functionality Python lambdas are only a shorthand notation if youre too lazy to ... | Why can t lambda expressions contain statements? |
situations where performance matters making a copy of the list just to sort it would be wasteful Thereforelistsortsorts the list in place In order to remind you of that fact it does not return the sorted list This way you wont be fooled into accidentally overwriting a list when you need a sorted copy but also need to... | Why doesn t list sort return the sorted list? |
tarting in Python 38 you canAssignment expressions using the walrus operatorassign a variable in an expressionwhilechunkfpread200printchunkSeePEP 572for more information | Why can t i use an assignment in an expression? |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 15