Saturday, March 8, 2014

Python Study Note: Data Structure - Tuple

In my opinion, tuple is similar as List, while it is "immutable", that means, its elements cannot be changed.

For example,
    a = [1,2,3] is a list
    b = (1,2,3) is a tuple

We can run: a[0] = 1000;
However, we cannot run b[0] = 1000;

Basically, once the tuple is set, it is set!

If we try to understand the List and Tuple in C, the List variable name is more like a pointer; while the tuple is more like a well-structured box. 

1. Why list is like Pointer?
    a = [1,2,3];
    b = a;
    a[1] = 1000;
    then b value also changes to [1,1000,3].

2. List in Tuple
    a = [1,2,3]; b = [4,5,6]; c = (a,b); 
    a[0] = 1000;
    then the tuple's value also changes to ([1000,2,3], [4,5,6]), this may because the tuple has the list's name/pointer fixed, however, its pointed space's value could change. 
    If we want to make a "real" copy of one list, we can do:
    a = [1,2,3]; b = list(a); 

    Done ~

No comments:

Post a Comment