References in Python

Source: Internet
Author: User
Tags python list

As a Python beginner, today is a Python list and dictionary reference problems tortured for a long time, but actually understand the reason is also very simple, recorded in this memo.

First endorse the Reference object problem in Python:

1. Python does not allow programmers to choose whether to use a value or to pass a reference. Python parameter passing is definitely a way to "pass an object reference". In fact, this approach is equivalent to a synthesis of value-passing and reference. If a function receives a reference to a mutable object (such as a dictionary or a list), it can modify the original value of the object-the equivalent of passing the object through a "pass reference". If a function receives a reference to an immutable object (such as a number, character, or tuple), it cannot directly modify the original object-the equivalent of passing the object through a "pass value".

2. When people copy a list or dictionary, the reference to the object list is duplicated, and if the referenced value is changed, the original parameter is modified.

3. To simplify memory management, Python uses a reference counting mechanism for automatic garbage collection, and each object in Python has a reference count that counts how many times the object has been referenced in different locations. Whenever a Python object is referenced, the corresponding reference count increases by 1, and whenever a Python object is destroyed, the corresponding reference is reduced by 1, and the Python object is actually removed from memory only if the reference count is zero.

List reference

Let's look at 2 examples at a glance:

[Python]View Plaincopy
  1. def add_list (p):
  2. p = p + [1]
  3. P1 = [1,2,3]
  4. Add_list (p1)
  5. print P1
  6. >>> [1, 2, 3]
  7. def add_list (p):
  8. p + = [1]
  9. P2 = [1,2,3]
  10. PROC2 (p2)
  11. Print P2
  12. >>>[1, 2, 3, 1]

This is mainly because the "=" operator creates a new variable to hold the assignment result, and then points the reference name to the left of "=", modifying the original P reference so that p becomes a reference to the new assignment variable. and + = does not directly modify the original P reference content, in fact, + + and = in Python using a different implementation function.

Dictionary references

[Python]View Plaincopy
  1. 1 A = []
  2. 2 B = {' num ':0, ' sqrt ':0}
  3. 3 Resurse = [1,2,3]
  4. 4 for i in resurse:
  5. 5 b[' num '] = i
  6. 6 b[' sqrt ') = i * I
  7. 7 A.append (b)
  8. 8 Print a
  9. 9 >>> [{' num ': 3, ' sqrt ': 9}, {' num ': 3, ' sqrt ': 9}, {' num ': 3, ' sq RT ': 9}]

But the result we actually want is this:

>>> [{' num ': 1, ' sqrt ': 1}, {' num ': 2, ' sqrt ': 4}, {' num ': 3, ' sqrt ': 9}]

This is because the element in a is a reference to B. Can be modified to:

1 A = []2 resurse = [1,2,3]3 for i in Resurse:4   a.append ({"num": I, "sqrt": I * i})

Instance

Next you can see an example of torturing me for half a day:

Define a family spectral dictionary: value is the parent of key. To write a function, enter the name of the person and give all of the ancestors ' names.

The beginning of the practice:

 1 ada_family = {' Judith Blunt-lytton ': [' Anne Isabella Blunt ', ' Wilfrid Scawen Blunt '], 2 ' Ada King-milban Ke ': [' Ralph King-milbanke ', ' Fanny Heriot '], 3 ' Ralph King-milbanke ': [' Augusta Ada King ', ' William king-no  El '], 4 ' Anne Isabella Blunt ': [' Augusta Ada King ', ' William King-noel '], 5 ' Byron King-noel ': [' Augusta Ada king ', ' William King-noel '], 6 ' Augusta Ada King ': [' Anne Isabella Milbanke ', ' George Gordon Byron '], 7 ' George Gordon Byron ': [' Catherine Gordon ', ' Captain John Byron '], 8 ' John Byron ': [' Vice-Admiral John Byron ', ' Sophia trevannion ']} 9 Def ancestors (genealogy, person): The If person in genealogy:13 parents = genealogy[person]14 RE Sult = Parents15 for parent in parents:16 result + = Ancestors (genealogy, parent) + return ResU lt18 return []19 print ancestors2 (ada_family, ' Judith Blunt-lytton ') Print Ada_family21 22 #>>> [' Anne Isabella Blunt ', ' Wilfrid Scawen Blunt ', ' Augusta Ada King ', ' William King-noel ', ' Anne Isab ' Ella Milbanke ', ' George Gordon Byron ', ' Catherine Gordon ', ' Captain John Byron ', ' Catherine Gordon ', ' Captai ' n John Byron ', ' Anne Isabella Milbanke ', ' George Gordon Byron ', ' Catherine Gordon ', ' Captain John Byron ', ' Catherin  E Gordon ', ' Captain John Byron ', ' Catherine Gordon ', ' Captain John Byron ', ' Catherine Gordon ', ' Captain John Byron ']29 # #>>> {' Ralph King-milbanke ': [' Augusta ada King ', ' William King-noel '],31 # ' Ada King-milbanke ': [' Ralph King-milbanke ', ' Fanny Heriot '],32 # ' Anne Isabella Blunt ': [' Augusta Ada King ', ' William King-noel ', ' Anne Isabella Milbanke ', ' George Gordon Byron ', ' Catherine Gordon ', ' Captain John Byron ', ' Catherine Gordon ', ' Captain John Byr ' On '],33 # ' Augusta Ada King ': [' Anne Isabella Milbanke ', ' George Gordon Byron ', ' Catherine Gordon ', ' Captain John Byron ', ' Catherine Gordon ', 'Captain John Byron '],34 # ' Judith blunt-lytton ': [' Anne Isabella Blunt ', ' Wilfrid Scawen Blunt ', ' Augusta Ada King ', ' W Illiam King-noel ', ' Anne Isabella Milbanke ', ' George Gordon Byron ', ' Catherine Gordon ', ' Captain John Byron ', ' Catherine G Ordon ', ' Captain John Byron ', ' Anne Isabella Milbanke ', ' George Gordon Byron ', ' Catherine Gordon ', ' Captain John Byron ', ' Catherine Gordon ', ' Captain John Byron ', ' Catherine Gordon ', ' Captain John Byron ', ' Catherine Gordon ', ' Captain John Byron '],35 # ' Byron king-noel ': [' Augusta Ada King ', ' William King-noel '],36 # ' George Gordon Byron ': [' Catherine Gordon ' , ' Captain John Byron '],37 # ' John Byron ': [' Vice-Admiral John Byron ', ' Sophia trevannion '}

This is not the result I want, began to check for a long time are unclear so, until I suddenly remembered to print the dictionary ada_family, only to find that the dictionary is not the original value, then, I reacted to the reason is quoted. Since the result we use is actually a reference to the value list in the dictionary, the result is changed, and the ada_family dictionary is changed, resulting in incorrect results (with many duplicates).

Change to the following notation.

 1 Def ancestors (genealogy, person): 2 If person in genealogy:3 parents = Genealogy[person] 4 result = Parents 5 for the parent in parents:6 result = result + Ancestors2 (genealogy, parent) 7 return Result 8 return [] 9 #>>> [' Anne Isabella Blunt ', ' Wilfrid Scawen Blunt ', ' Augusta Ada King ', one # ' Wil Liam King-noel ', ' Anne Isabella Milbanke ', ' George Gordon Byron ', ' Catherine Gordon ', ' Captain John Byron ']13 #14 #>>> {' Ralph King-milbanke ': [' Augusta Ada king ', ' William King-noel '], ' Ada King-milbanke ': [' Ralph King -milbanke ', ' Fanny Heriot '], "Anne Isabella Blunt ': [' Augusta Ada King ', ' William King-noel '], ' Augusta Ad ' A King ': [' Anne Isabella Milbanke ', ' George Gordon Byron '], # ' Judith Blunt-lytton ': [' Anne Isabella Blunt ', ' Wilfri D Scawen Blunt ' Byron king-noel ': [' Augusta Ada King ', ' William King-noel '], ' George Gordon Byron ': [' C Atherine Gordon ', ' CaptaIn John Byron '], # ' John Byron ': [' Vice-Admiral John Byron ', ' Sophia trevannion '} 

The original dictionary content is not modified at this time, and the correct result is obtained.

Of course, we can also simply use the following method to achieve, avoid the trouble of reference:

1 Def ancestors (genealogy, person): 2     if person in genealogy:3         parents = genealogy[person]4         return parents + A Ncestors (Genealogy,parents[0]) + ancestors (Genealogy,parents[1]) 5     return []

Here are some things to remember about lists and dictionaries:

list list[]

Assignment List1[3:4]=[a,b]

Len (list) length

Del List Delete Object

Supported Methods for list objects:

Appending a single object x to the tail of append (x), using multiple objects causes an exception.

COUNT (x) returns the number of times the object x appears in the list

Extend (l) adding items from the list L to the table

Index (x) returns the indexes of the first table item matching the object x, which produces an exception if no match

Insert (I,X) element in index ' I ' Money Insert object X

Pop (x) removes the table entry for index x in the list and returns the value of the same table entry, with no parameter removed last

Remove (x) removes the first element of the table match object x, no matching exception

Reverse () Reverses the order of list elements

Sort () Sorts the list

Also simple to use + to implement list connection: [3,4] + [[1,2],5,6]--[3,4,[1,2],5,6]

Delete Duplicates in list: M = List (set (L)), Python set is similar to other languages, is a set of unordered and distinct elements

dictionary dictionary{name:value,...}

How to + + + dictionaries

Has_keys (x) If an x in the dictionary returns true

Keys () returns a list of keys

VALUES () returns a list of value

Dict.items () returns a list of tuples. Each tuple has a dictionary of dict keys and corresponding values that make up the

Clear () Delete all entries for the dictionary

Copy () returns a copy of the high-level structure of the dictionary, but does not copy the embedded structure and copies references to those structures.

Update (x) updates the contents of the dictionary with key/value pairs in dictionary x.

Get (X[,y]) returns the key X. Returns none if not found

Built-in object type conversions

STR (x) translates object x into a string

List (x) returns the object sequence x as a list. For example ' Hello ' returns [' H ', ' e ', ' l ', ' l ', ' o '], convert tuple to list

Tuple (x) returns the object sequence x as a tuple

int (x) converts strings and numbers to integers, and instead of rounding floating point

Long (x) converts strings and numbers to long-shaped

Float (x) converts STR and num to floating-point objects

Complex x (x, y) to do the real part, Y to create a complex number imaginary part

Hex (x) converts an integer or long integer to a hexadecimal string

Oct (x) converts an integer or long integer to an octal string

Ord (x) returns the ASCII value of the character X

Chr (x) returns the character represented by the ASCII code x

Min (x[,...]) returns the smallest element in a sequence

Max (x[,...]) returns the largest element in a sequence

References in Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.