How can I switch contents of lists? - python

I have two lists, a and b.
I want to reassign the content of a into b and the content of b into a.
or in other words, after running a few operations with two lists, I want to switch the names of the lists. so that the list that was named a would now be named b, and the list that was named b would now be named a.
this way is obviously wrong:
a=b
b=a
(because they are both b now)
so, is there a right way to do this?

python lets you do that as follows:
a, b = b, a
Example
a = [1,2,3]
b = [4,5,6]
a, b = b, a
>>> print a
[4,5,6]
>>> print b
[1,2,3]
This is because the expression on the right hand side is evaluated first and then assigned to variables on the left.

This might be not necessary for you, but good to remember that:
a = [1, 2, 3]
b = [3, 4, 5]
c = a # now 'c' points to the same list as 'a'
a[0] = 0 # let's change the first element
print a
# [0, 2, 3]
print c
# now let's use multiple assigment:
a, b = b, a
print a
# [3, 4, 5]
print c
# [0, 2, 3]
# list didn't change, but 'a' now point do different list
# but 'c' still point to the same, unchanged list, the one
# that is now referenced by 'b'
Above solution is fast and usually the best. But if you have the same list (or other mutable data structure) referenced by other names, you may swap contents of list instead:
a = [1, 2, 3]
b = [3, 4, 5]
c = a
a[0] = 0
a[:], b[:] = b[:], a[:] # now we actually swap contents
# 'a' and 'c' still point to the same list,
# but values are from 'b' list
print a
# [3, 4, 5]
print b
# [0, 2, 3]
print c
# [3, 4, 5]

Related

Isn't there a multidimensional set library in Python?

I want to do a multidimensional set compute.
For example:
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
This one's set.difference is:
c = a - b
c = [1, 2]
But when it's multi-dimensional, I don't know.
How do I do this?
a = [['a',1],['b',2],['c',3]]
b = [['a',2],['c',7],['d',5]]
I want to calculate around a string.
I wish I could get this value.
c = a - b
c = [['b',2]]
You can try
[i for i in a if i[0] in {str(i[0]) for i in a}.difference({str(i[0]) for i in b})]
Output
[['b', 2]]
This code will return the item that is in the list a by the first elements that is not in the b list.

Why doesn't the copy of a list in a function work?

b = [0]
def copyalist(b):
b = [1, 2, 3]
print(b)
copyalist(b)
print(b)
The outputs are below:
[1, 2, 3]
[0]
The first line indicates that in the function, b was set to [1, 2, 3];
However, when you print(b) out of the function,the second output says that b is still [0].
I don't understand that, why the outer b is not changed?
I also tried b = copy.deepcopy([1, 2, 3]), the outputs are the same.
However, the following code works well:
b = [0]
def copyalist(b):
b += [1, 2, 3]
print(b)
copyalist(b)
print(b)
The outputs are below:
[0, 1, 2, 3]
[0, 1, 2, 3]
This code:
def copyalist(b):
b = [1, 2, 3]
print(b)
will only mean to remap the variable name b to a new list, but not modifying the original b. If you mean to modify the original list, you have to explicitly tell Python to replace the actual content. The way to do is:
def copyalist(b):
b[:] = [1, 2, 3]
print(b)
In python, lists are passed as function arguments only by reference, i.e., only the memory address of the first element is given. When defining a new b inside the function, you just change the position in memory to which the inner variable b refers, but the outer b still points to the original position. Vice versa, when you do b += [1, 2, 3], you change the content inside the cell referenced by the inner b and, since inner and outer b point to the same cells, it reflects in a change of the outer b as well.
This is due to a difference in global and local variables. You can add global to your function to get the desired result.
b = [0]
def copyalist():
global b
b = [1, 2, 3]
print(b)
copyalist()
print(b)
OUTPUT
[1, 2, 3]
[1, 2, 3]
A more in depth summary is here
b = copyalist(b)
and return b in the function
def copyalist(b):
b = [1, 2, 3]
return(b)
When you are defining something in a function it is only used inside that function.

The generator works strange

a = [1, 2, 3]
b = (c for c in a if c in a)
a = [2, 3, 4]
print(list(b))
def d(expr):
for c in expr:
if c in expr:
yield c
a1 = [1,2,3]
t = d(a1)
a1 = [2,3,4]
print(list(t))
output:
[2, 3]
[1, 2, 3]
question:
1) in the first variant, the cycle retains the old value of the list ([1,2,3]), but the conditional expression takes a new list a([2,3,4]).
2) how my own generator give me other result than generative expression?
For example, I replaced a on the real lists of the first example, I hope this will be more clear my first question.
a = [1, 2, 3]
b = (c for c in [1,2,3] if c in [2, 3, 4])
a = [2, 3, 4]
print(list(b))
Output:
[2,3]
As per PEP 289, we can rewrite your generator expression as follows:
# b = (c for c in a if c in a)
def __gen(expr):
for c in expr:
if c in a:
yield c
b = __gen(iter(a))
Here, a reference to [1, 2, 3] for use in the for loop is captured immediately (when you create b), but the if c in a check uses the new global a which is equal to [2, 3, 4].
On the other hand, when you write a generator function, a1 is passed to the function and stored for later use in both for and if x in y expressions. Assigning a1 = [2, 3, 4] has no effect.
To make the function do the same thing as the generator expression, all you need to do is replace if c in expr with if c in a1.

List of List, want to output variable, not value

I have a list of lists like so:
a = [1, 2, 3]
b = [2, 3, 4]
c = []
append blah blah blah
I currently am doing:
for x in c:
print(x)
and it is outputing [1, 2, 3]. How would i get it to output 'a' instead?
There are a few ways to achieve what you want. The first suggestions require using a different data structure. The last suggestion is for demonstration purposes ONLY and should NEVER BE USED.
Option 1. Store you data in a dictionary:
my_data = {"a": [1, 2, 3], "b": [2, 3, 4]}
my_data["c"] = [my_data.get('a'), my_data.get('b')]
Then you would simply iterate over the key, value pairs.
>>> for name, value in my_data.items():
... print name, value
...
a [1, 2, 3]
c [[1, 2, 3], [2, 3, 4]]
b [2, 3, 4]
The dictionary has no useful ordering, so if you wanted it ordered you could use an OrderedDict, or another data structure like a list of tuples.
Or you could sort them before you iterate:
for name, value in sorted(my_data.items()):
print name, value
You could also create the dictionary after the variables are assigned
>>> a = [1, 2, 3]
>>> b = [2, 3, 4]
>>> c = [a, b]
>>> my_data = {"a": a, "b": b, "c": c}
Option Terrible. The very hackish way to do this (and only for demonstration purposes) is to use locals()
>>> a = [1, 2, 3]
>>> b = [2, 3, 4]
>>> c = [a, b]
>>> for name, value in locals().items():
... if len(name) != 1:
... continue
... print name, value
...
a [1, 2, 3]
c [[1, 2, 3], [2, 3, 4]]
b [2, 3, 4]
You are printing a. Your list c is actually
C = [[1,2,3], [2,3,4]]
If you modify a before printing c. The new values in a will be shown. As python passes by reference and c contains a reference to a
If you want to print the variable name see Can I print original variable's name in Python? and How can you print a variable name in python?
However the answers there say you should not do it.
You are telling it to print the complete contents of c which contains the objects a and b which are indeed
[1, 2, 3]
[2, 3, 4]
You are saying that you want to print the string 'a'
To do that you would have to define
c = ['a', 'b']
which is completely different.

python [:] notation and range

I've been tasked with converting some python code over to Java. I came across some notation I'm not familiar with and can't seem to find any information on. I'm guessing this is a lack of keywords on my part.
I've sanitized the code and hard coded some basic values for simplicity.
index_type = c_int * 1000 #size of int, basically 1000 integers?
indexes = index_type() # not entirely sure what this does
indexes[:] = range(2000, 3000)[:] # no idea
# c_int equals 4
The logic doesn't really matter to me, I'm just trying to figure out what's going on in terms of datatypes and converting to Java.
This is called "slicing". See the tutorial sections on Strings and Lists for a good description of how it works. (In your example, it's actually a ctypes array that's being sliced, not a list, but they work the same way. So, for simplicity, let's talk about lists.)
The notation indexes[:] is a slice of the entire list. So, you can do this:
a = [1, 2, 3]
b = a[:]
… to get a copy of the whole list, and this:
a[:] = [4, 5, 6]
… to replace the contents of the whole list.
You may wonder how this is different from just using a itself. The difference is that in the first case, b = a doesn't copy the list, it just makes another reference to the same list, and in the second case, a = [4, 5, 6] doesn't mutate the list, it rebinds a to refer to a new list. Here's an example that shows the difference:
>>> a = [1, 2, 3]
>>> b = a # b is now the same list as a
>>> a[0] = 10 # so changing that list is visible to b
>>> b
[10, 2, 3]
>>> a = [1, 2, 3]
>>> b = a[:] # b is now a new list, with a copy of a
>>> a[0] = 10 # so changing the original list doesn't affect b
>>> b
[1, 2, 3]
>>> a = [1, 2, 3]
>>> b = a # b is now the same list as a
>>> a = [4, 5] # but now a is a different list
>>> a[0] = 10
>>> b
[1, 2, 3]
>>> a = [1, 2, 3]
>>> b = a # b is now the same list as a
>>> a[:] = [4, 5] # and we've replaced the contents
>>> b
[4, 5]
You may wonder why anyone would use range(2000, 3000)[:] on the right side of the assignment.
Well, I wonder the same thing.
If this is Python 2.x, range(2000, 3000) is a brand-new list. You replace the contents of indexes with the contents of that range list, then give up your only reference to the range list. There is no way anyone could possibly end up sharing it, so there is no good reason to make an extra copy of it, unless you're worried that your computer has too much CPU and too much RAM and might be getting bored.
If this is Python 3.x, range(2000, 3000) is a smart range object. And range(2000, 3000)[:] is a new and equal range object. The copying this time is a lot cheaper, but it's exactly as unnecessary.
The other answers are talking about what x[:] means as an expression. But when this notation is used as the target of an assignment (i.e., on the left side of the =), it means something different. It is still a slice of the object, but it doesn't create a copy; rather, it assigns the given value (the right hand side) to the specified "part" of the object. If you use [:], the slice is the whole object, so its contents will be replaced by what you pass.
An example:
>>> x = [1, 2, 3]
>>> x[:] = [8, 8]
>>> x
[8, 8]
Notice that you can replace the contents by new contents of different length.
If you use a partial slice, only part of the contents will be replaced:
>>> x = [1, 2, 3, 4]
>>> x[1:3] = [8, 8, 88]
>>> x
[1, 8, 8, 88, 4]
The notation:
[a:b]
Is a range that starts at a and ends at b. When you leave one of them blank, it counts as "beginning" and "end", respectively.
Basically, your indexes is a list of values, each one has a number to associate with it that shows its order inside indexes. It starts at 0 and progresses until the end. The line of code:
indexes[:]
Simply means
"first value of indexes to last value of indexes"
I hope this helps,
happy coding!
It means getting a COPY of the original list, since lists are mutable in python, for example
>>a = [1,2,3]
>>b = a
>>a[0] = 3
>>a
[3, 2, 3]
>>b
[3, 2, 3]
>>b = a[:]
>>a[0] = 0
>>a
[0, 2, 3]
>>b
[3, 2, 3]
[:] is an example of slice notation, Python's way to specify any number of items in a sequence. [:] specifies the entire sequence. The notation is succinct and powerful in what it can express. Some other possible forms are:
sequence[n] #an index to one item (not a slice)
sequence[n:] #the nth item to the end of the sequence
sequence[:n] #all items until the nth item (exclusive)
sequence[m:n] #the mth item until the nth item (exclusive)
sequence[:] #all items
sequence[::2] #every other item
sequence[::-1] #all items in reverse order
When slicing is used to modify items in a sequence, the item(s) are modified:
>>> a = [1, 2, 3]
>>> a[0:1] = [4] #same as a[0] = 4
>>> a
[4, 2, 3]
>>> a[:] = [1, 2, 3, 4] #the sequence can be made larger
>>> a
[1, 2, 3, 4]
>>> a[:] = [] #or smaller
>>> a
[]
When slicing is used to read items in a sequence, a shallow copy of the item(s) are returned instead of a reference to the item. The term shallow copy means that if a copied item is itself a sequence, the item will refer to the original sequence, not a copy of it:
For instance:
>>> a = [1, 2, 3]
>>> b = a[0]
>>> b #b has the same value as, but does not reference the same object as a[0]
1 #this is a copy of a[0]
>>> a = [1, 2, 3]
>>> b = a[:]
>>> b #b has the same values as, but does not reference the same object as a
[1, 2, 3] #this is a copy of list a
>>> a = [1, 2, 3]
>>> b = [a, 2, 3]
>>> c = b[:] #c is a hallow copy of b
>>> c
[[1, 2, 3], 2, 3]
>>> b[:] = [] # modifying b does not affect c
>>> c
[[1, 2, 3], 2, 3]
>>> a[0] = 4 # modifying a will affect a in c
>>> c
[[4, 2, 3], 2, 3]

Categories