Short answer: Not really, but there might be something close enough.
The problem is, under the covers, a is a pointer-to-a-list, and l is a pointer-to-a-list-of-pointers-to-lists. When you a = l[0], what that actually translates to at the CPU is "dereference the pointer l, treat the resulting region of memory as a list object, get the first object (which will be the address of another list), and set the value of pointer a to that address". Once you've done that, a and l[0] are only related by concidence; the are two separate pointers that happen, for the moment, to point at the same object. If you assign to either variable, you're changing the value of a pointer, not the contents of the pointed-to object.
Broadly speaking, there's a few ways the computer could practically do what you ask.
- Modify the pointed-to object (list) without modifying either pointer. That's what the
appendfunction does, along with the many other mutators of python lists. If you want to do this in a way that perhaps more clearly expresses your intent, you could dol[0][:] = [1,2]. That's a list copy operation, copying into the object pointed to by bothl[0]anda. This is your best bet as a developer, though note that copy operations are O(n). - Implement
aas a pointer-to-a-pointer-to-a-list that is automatically dereferenced (to merely a pointer-to-list) when accessed. This is not, AFAIK, something Python provides any support for; almost no language does. In C you could saylist ** a = &(l[0]);but then any time you want to actually do anything withayou'd have to use*ainstead. - Tell the interpreter to observe that
ais an alias tol[0], rather than its own, separate variable. As far as I know, Python doesn't support this either. In C, you could do it as#define a (l[0])though you'd want to#undef awhen it went out of scope. - Rather than making
aa list variable (which is implemented as a pointer-to-list), make it a function:a = lambda: l[0]. This means you have to usea()instead ofaanywhere you want to get the actual content ofl[0], and you can't assign tol[0]througha()(or throughadirectly). But it does work, in Python. You could even go so far as to use properties, which would let you skip the parentheses and assign througha, but at the cost of writing a bunch more code to wrap the lists (I'm not aware of a way to attach properties to lists directly, though one might exist, so you'd instead have to create a new object wrapping the list).
Short answer: Not really, but there might be something close enough.
The problem is, under the covers, a is a pointer-to-a-list, and l is a pointer-to-a-list-of-pointers-to-lists. When you a = l[0], what that actually translates to at the CPU is "dereference the pointer l, treat the resulting region of memory as a list object, get the first object (which will be the address of another list), and set the value of pointer a to that address". Once you've done that, a and l[0] are only related by concidence; the are two separate pointers that happen, for the moment, to point at the same object. If you assign to either variable, you're changing the value of a pointer, not the contents of the pointed-to object.
Broadly speaking, there's a few ways the computer could practically do what you ask.
- Modify the pointed-to object (list) without modifying either pointer. That's what the
appendfunction does, along with the many other mutators of python lists. If you want to do this in a way that perhaps more clearly expresses your intent, you could dol[0][:] = [1,2]. That's a list copy operation, copying into the object pointed to by bothl[0]anda. This is your best bet as a developer, though note that copy operations are O(n). - Implement
aas a pointer-to-a-pointer-to-a-list that is automatically dereferenced (to merely a pointer-to-list) when accessed. This is not, AFAIK, something Python provides any support for; almost no language does. In C you could saylist ** a = &(l[0]);but then any time you want to actually do anything withayou'd have to use*ainstead. - Tell the interpreter to observe that
ais an alias tol[0], rather than its own, separate variable. As far as I know, Python doesn't support this either. In C, you could do it as#define a (l[0])though you'd want to#undef awhen it went out of scope. - Rather than making
aa list variable (which is implemented as a pointer-to-list), make it a function:a = lambda: l[0]. This means you have to usea()instead ofaanywhere you want to get the actual content ofl[0], and you can't assign tol[0]througha()(or throughadirectly). But it does work, in Python. You could even go so far as to use properties, which would let you skip the parentheses and assign througha, but at the cost of writing a bunch more code to wrap the lists (I'm not aware of a way to attach properties to lists directly, though one might exist, so you'd instead have to create a new object wrapping the list).
If a = l then calling a[0] in that case would yield [1,2], however, you are deleting the list that “a” was referencing, therefore the reference is destroyed as well. You need to either make a = l and call a[0] or reset the reference by calling a = l[0] again.
python - How to pass a list element as reference? - Stack Overflow
python - How can I get the reference of a List element? - Stack Overflow
python - Reference to an element in a list - Stack Overflow
Python referring to an item in a list from another list - Stack Overflow
The explanations already here are correct. However, since I have wanted to abuse python in a similar fashion, I will submit this method as a workaround.
Calling a specific element from a list directly returns a copy of the value at that element in the list. Even copying a sublist of a list returns a new reference to an array containing copies of the values. Consider this example:
>>> a = [1, 2, 3, 4]
>>> b = a[2]
>>> b
3
>>> c = a[2:3]
>>> c
[3]
>>> b=5
>>> c[0]=6
>>> a
[1, 2, 3, 4]
Neither b, a value only copy, nor c, a sublist copied from a, is able to change values in a. There is no link, despite their common origin.
However, numpy arrays use a "raw-er" memory allocation and allow views of data to be returned. A view allows data to be represented in a different way while maintaining the association with the original data. A working example is therefore
>>> import numpy as np
>>> a = np.array([1, 2, 3, 4])
>>> a
array([1, 2, 3, 4])
>>> b = a[2]
>>> b
3
>>> b=5
>>> a
array([1, 2, 3, 4])
>>> c = a[2:3]
>>> c
array([3])
>>> c[0]=6
>>> a
array([1, 2, 6, 4])
>>>
While extracting a single element still copies by value only, maintaining an array view of element 2 is referenced to the original element 2 of a (although it is now element 0 of c), and the change made to c's value changes a as well.
Numpy ndarrays have many different types, including a generic object type. This means that you can maintain this "by-reference" behavior for almost any type of data, not only numerical values.
Python doesn't do pass by reference. Just do it explicitly:
l[1] = ModList(l[1])
Also, since this only changes one element, I'd suggest that ModList is a confusing name.
It's not possible, because integers are immutable, while list are mutable.
In b = a[1] you are actually assigning a new value to b
Demo:
>>> a = 2
>>> id(a)
38666560
>>> a += 2
>>> id(a)
38666512
You can like this,
>>> a = [1,2,3]
>>> b = a
>>> a[1] = 3
>>> b
[1, 3, 3]
>>> a
[1, 3, 3]
>>> id(a)
140554771954576
>>> id(b)
140554771954576
You can read this document.
As jonrsharpe said, you can do what you want by using mutable elements in your list, eg make the list elements lists themselves.
For example
a = [[i] for i in xrange(5)]
print a
b = a[3]
print b[0]
a[3][0] = 42
print a
print b[0]
b[:] = [23]
print a
print b
output
[[0], [1], [2], [3], [4]]
3
[[0], [1], [2], [42], [4]]
42
[[0], [1], [2], [23], [4]]
[23]
Everything in python is a reference. After all those statements are executed, listB[1] and listA[1] are literally the same object. (you can check, by calling id(listB[1]) and id(listA[1]).
The reason listA[0] and listB[0] are different is merely because you put a different reference into that spot.
Judging from your description, you don't want to a listA that stores references to the objects in listB. What you want is a listA that is a view of listB. I believe you have only two options:
Create a special sequence that internally stores a reference to
listA, and whose__getitem__and__setitem__methods perform lookups intolistAwhen invoked.Create special a special reference types that contains something like a "sequence and index". Put these references into
listA. But, to modifylistBthroughlistA, you'll have to invoke some sort of "get" and "set" members of these reference objects.
You can't. First of all integers are immutable and they don't work like integers in C/C++. You can't get pointer/reference to an integer and then change it (I mean you can, you always have a reference, but it is usually reference to a single object; check this x = 1; y = 1; print id(x), id(y); id values should be the same and they are memory addresses). What you can do is get index of elements in listB and change the list, e.g.:
listA = [0, 1]
listB[listA[0]] = 0
But probably you are trying to do something you are not supposed to do, because Python works differently than C++. What are you trying to achieve?
my_list = [-3, 3]
def change_list(my_list):
my_list = 1
change_list(my_list)
print(my_list)This outputs: [-3, 3]
Why doesn't the global my_list change?
Lists are already passed by reference, in that all Python names are references, and list objects are mutable. Use slice assignment instead of normal assignment.
def add(L1, L2, L3):
L3[:] = L1 + L2
However, this isn't a good way to write a function. You should simply return the combined list.
def add(L1, L2):
return L1 + L2
L3 = add(L1, L2)
You can achieve this with:
L3[:] = L1 + L2
Test Code:
def add(L1, L2, L3):
L3[:] = L1 + L2
L3 = []
add([1], [0], L3)
print(L3)
Results:
[1, 0]
what does " lists hold the reference of value " mean. i'm a total beginner in programming, and i'm learning python, and i passsed by through this which i didn't understand.
any help please.
You cannot pass anything by value in Python. If you want to make a copy of a, you can do so explicitly, as described in the official Python FAQ:
b = a[:]
To copy a list you can use list(a) or a[:]. In both cases a new object is created.
These two methods, however, have limitations with collections of mutable objects as inner objects keep their references intact:
>>> a = [[1,2],[3],[4]]
>>> b = a[:]
>>> c = list(a)
>>> c[0].append(9)
>>> a
[[1, 2, 9], [3], [4]]
>>> c
[[1, 2, 9], [3], [4]]
>>> b
[[1, 2, 9], [3], [4]]
>>>
If you want a full copy of your objects you need copy.deepcopy
>>> from copy import deepcopy
>>> a = [[1,2],[3],[4]]
>>> b = a[:]
>>> c = deepcopy(a)
>>> c[0].append(9)
>>> a
[[1, 2], [3], [4]]
>>> b
[[1, 2], [3], [4]]
>>> c
[[1, 2, 9], [3], [4]]
>>>
This one might be a bit hard to describe, but the high-level logic is...
For a given list of random numbers (n), take the 20th value, and determine what percentage of the previous 19 numbers are below the 20th value. Repeat this for the 21st value, 22nd, etc. It will always be the previous 19 numbers.
I've got an algorithm that does this, but I need to iterate over a stupidly large amount of data. If I ran it right now, even with splitting across 6 processes, it's still going to take 2 weeks to complete. That's not practical for my purposes.
I came up with a faster algorithm, but I'm having trouble implementing it. It involves tracking merely the change in the number being compared to so that it doesn't have to iterate over all previous 19 numbers. This would scale very for what I need and should reduce the number of times I have to iterate over the data by billions.
I can almost achieve this by tracking the indexes of the items I'm looking at. The problem is that I have to insert items into the middle of this list which invalidates the index I had saved because the real value got bumped up to a higher index. If I could simply use it by reference, this wouldn't happen.
I've considered using dictionaries, but that would involve me making keys out of every number in the system down to at least 0.0001. That doesn't seem practical and I'm skeptical it would even work.
Hope I explained this well. Would appreciate any help.
You misunderstood. There are 5 distinct references. If those 5 references all point to the same nested list and you alter that nested list, you can see the change reflected through all those references.
You didn't change a nested list here. You changed one of the references.
Think of references as nametags. You can put more than one nametag on an object:
nametag_a+-----------+
+---v--+
|object|
+---^--+
|
nametag_b+-----------+
You can 'look' at the object through either reference. Assignment is simply attaching a reference to an object. If a reference pointed to an object before, it is detached from that object and now points to another object:
nametab_b = another_object
results in
nametag_a+-----------+
+---v--+
|object|
+------+
nametag_b +--------------+
+-------->another_object|
+--------------+
The numbered indices in a list are references to; so instead of nametag_a, you have 0, and 1, etc.
The other question talks about nested lists. There you have multiple references to a single list object:
# indices in a list on the left referencing another list
0+---------------------------+
|
|
1+------------------------+ |
| |
+---------v--v-----------+
2+--------------> list with more indices |
+---------^--^-----------+
| |
3+------------------------+ |
|
|
4+---------------------------+
If you make a change to the list with more indices contents, then you'll see those changes through any of the 5 references in the outer list
Please read Facts and myths about Python names and values by Ned Batchelder, which explains this in more detail.
Great site to further understanding the situation.
Python Tutor

Sorry if this is something I should be able to find on my own, but I'm not finding what I need elsewhere.
I have a list A containing nine integers. I want to create a second list B such that it's values are references to A[1:8:3]. In essence, if the value stored in A[1] is changed, I want the value of B[0] to change automatically.
I hope that makes sense.
In Python, assignment operator binds the result of the right hand side expression to the name from the left hand side expression.
So, when you say
a = Foo(2)
b = [a]
you have created a Foo object and refer it with a. Then you create a list b with the reference to the Foo object (a). That is why b[0].value prints 2.
But,
a = Foo(3)
creates a new Foo object and refers that with the name a. So, now a refers to the new Foo object not the old object. But the list still has reference to the old object only. That is why it still prints 2.
b[0] points to the object you initially created with Foo(2). When you do a = Foo(3), you create a new object and call it a. You did not change b in any way.
The behavior is because of exactly what you said: b holds a reference to an object. It does not hold hold a reference to the name you used to refer to that object. So the object in b[0] does not know anything about any variable called a. Assigning a new value to a has no effect on b.