Python List Overwrites

Python List Overwrites thumbnail
An incomplete understanding of lists leads to problems in later programs.

Python lets programmers create objects called lists to store and recall multiple items when called upon. These objects are very useful, but the way that Python handles objects and variables creates a few pitfalls that both novice and intermediate programmers should be aware of before they find data elements in their lists being mysteriously overwritten with other data.

  1. Python Lists

    • Python's list object behaves more like Java's ArrayList object than it does a conventional array. The programmer does not have to declare the size of the array when he creates it, and the Python interpreter will automatically increase the list's size to accommodate more entries that the user appends. Python lists are also significantly more flexible than other arraylike data structures in that they can hold different objects and variable data types at the same time.

    Python Objects

    • Like arrays in other languages, programmers can choose to place elements inside a Python list by directly assigning the data to a particular index number in the list. He does this with the syntax "list[n] = new-data" where "list" is the name of the list object, "n" is the element number the programmer is assigning the data to, and "new-data" is the data the programmer is assigning to the list element. If there is data in the array element, it will be overwritten.

    Class Lists

    • One way that Python programmers accidentally overwrite entire lists, rather than specific components, is when they declare a list as a class list instead of a method list. When the Python interpreter instantiates multiple objects from a class declaration, they are independently functional, and changes in the variables of one will not affect the variables of another. However, when a programmer declares a list outside of any method, it is a class list. This list will be common to every object the interpreter makes from the class declaration, so changes in this list from one object will cause its values to change in every other object.

    Properly Copying Lists

    • A common mistake for programmers coming to Python from another languages is to the syntax "list-copy = list-original" to make a copy of "list-original" called "new-list." In Python, however, this leads to both "list-copy" and "list-original" pointing to the same values in memory. Consequently, when the programmer changes element values in "list-copy," he will find that his changes overwrote the original contents of "list-original" as well. The syntax "list-copy = list(list-original)" will copy the data contents of "list-original" into "list-copy" without changes in one affecting the other.

Related Searches:

References

  • Photo Credit Comstock/Comstock/Getty Images

Comments

Related Ads

Featured