Why two different simple list variables behave exactly like each other? [duplicate] - python-3.x

This question already has answers here:
Variable assignment and modification (in python) [duplicate]
(6 answers)
Closed 4 years ago.
Something very strange is happening to me. when i write this code down :
a = [3,2,4]
b = a
a.sort()
print(a)
print(b)
The variable "b" must be [3,2,4] and "a" must be [2,3,4].
But this result came out :
[2, 3, 4]
[2, 3, 4]
Why did it sort both of them?
I think it only happens to lists,because I tried to write the code below :
dots = dotsDetecter(param).getDots()
wholeDots = dots
The variable "dots" is gonna be a list but after that whatever I do to the "dots" list, wholeDots variable changes exactly like dots.
Does anybody now why it is happening?

b = a does not instantiate a new list, b is just an alias of a. So every operation on a will also affect b. You should do something like this:
def main():
a = [3, 2, 4]
b = list(a) # create new list initialized with a values
a.sort()
print(a)
print(b)

Related

How can i convert many variable to int in one line

I started to learn Python a few days ago.
I know that I can convert variables into int, such as x = int (x)
but when I have 5 variables, for example, is there a better way to convert these variables in one line? In my code, I have 2 variables, but what if I have 5 or more variables to convert, I think there is a way
You for help
(Sorry for my English)
x,y=input().split()
y=int(y)
x=int(x)
print(x+y)
You could use something like this .
a,b,c,d=[ int(i) for i in input().split()]
Check this small example.
>>> values = [int(x) for x in input().split()]
1 2 3 4 5
>>> values
[1, 2, 3, 4, 5]
>>> values[0]
1
>>> values[1]
2
>>> values[2]
3
>>> values[3]
4
>>> values[4]
5
You have to enter value separated with spaces. Then it convert to integer and save into list. As a beginner you won't understand what the List Comprehensions is. This is what documentation mention about it.
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
So the extracted version of [int(x) for x in input().split()] is similar to below function,
>>> values = []
>>> input_values = input().split()
1 2 3 4 5
>>> for val in input_values:
... values.append(int(val))
...
>>> values
[1, 2, 3, 4, 5]
You don't need to create multiple variables to save your values, as this example all the values are saved in values list. So you can access the first element by values[0] (0th element is the first value). When the number of input values are large, let's say 100, you have to create 100 variables to save it. But you can access 100th value by values[99].
This will work with any number of values:
# Split the input and convert each value to int
valuesAsInt = [int(x) for x in input().split()]
# Print the sum of those values
print(sum(valuesAsInt))
The first line is a list comprehension, which is a handy way to map each value in a list to another value. Here you're mapping each string x to int(x), leaving you with a list of integers.
In the second line, sum() sums the whole array, simple as that.
There is one easy way of converting multiple variables into integer in python:
right, left, top, bottom = int(right), int(left), int(top), int(bottom)
You could use the map function.
x, y = map(int, input().split())
print x + y
if the input was:
1 2
the output would be:
3
You could also use tuple unpacking:
x, y = input().split()
x, y = int(x), int(y)
I hope this helped you, have a nice day!

query on Python list comprehension [duplicate]

This question already has answers here:
Modify a list while iterating [duplicate]
(4 answers)
Can't modify list elements in a loop [duplicate]
(5 answers)
Closed 4 years ago.
I tried:
a = [0,1, 2, 3, 4, 5]
this works fine:
>>> for q in a:
... print(q)
...
0
1
2
3
4
But, if I try to change the (mutable) list objects like so, it doesn't work:
>>> for q in a:
... q = 0
...
>>> a
[0, 1, 2, 3, 4]
It seems to me that each time through the loop, q refers to a[n], as n ranges from 0 to 4. So, it would seem, setting q = 0 ought to make the list all value zero.
Any suggestions that are quite Pythonic?
Updating iterating variable inside loop does not itself update the iterator you iterate through.
for q in a:
q = 0
You are just modifying value of q, but do not touch the original list a.
To make all elements in list to 0, use a list-comprehension:
a = [0 for _ in a]

This for circle cannot delete every same elements in a list, I don't know why [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 4 years ago.
a = [1, 2, 2]
value = 2
for i in a:
if i == value:
a.remove(i)
I want to delete 2 same elements in a list. But the result tells me I just delete one of them. when I debug it, I find it only cycle 2 times, not 3 as I wish.
You can use a simple list comprehension for a 1-line solution:
In [2764]: a = [1, 2, 2]
In [2755]: value = 2
In [2768]: a = [i for i in a if i != value]
In [2769]: a
Out[2769]: [1]
You can write the above as :
ans = []
for i in a:
if i <> value:
ans.append(i)
OR, you can also use filter to remove all occurrences:
Python-2
In [2778]: filter(lambda x: x!= value, a)
Out[2778]: [1]
Python-3
In [5]: list(filter(lambda x: x!= value, a))
Out[5]: [1]
Here you don't have to use a comparison to remove a certain value from list
Here is a little modification to your code:
a = [1, 2, 2]
value = 2
try:
for i in a: a.remove (value)
except ValueError: pass
print (a)
Whenever the remove () function couldn't find the value you are looking for, it will raise a value error: ValueError: list.remove(x): x not in list. To eliminate this, surround it with a try except. That'll do the trick.
However there are more easier methods to use remove () function. For an example you could use while loop.
Look at this code:
a = [1, 2, 2]
value = 2
while value in a:
a.remove (value)
print (a)
Its far more easier.

Can you call 2 args from a function into another function? [duplicate]

So, Python functions can return multiple values. It struck me that it would be convenient (though a bit less readable) if the following were possible.
a = [[1,2],[3,4]]
def cord():
return 1, 1
def printa(y,x):
print a[y][x]
printa(cord())
...but it's not. I'm aware that you can do the same thing by dumping both return values into temporary variables, but it doesn't seem as elegant. I could also rewrite the last line as "printa(cord()[0], cord()[1])", but that would execute cord() twice.
Is there an elegant, efficient way to do this? Or should I just see that quote about premature optimization and forget about this?
printa(*cord())
The * here is an argument expansion operator... well I forget what it's technically called, but in this context it takes a list or tuple and expands it out so the function sees each list/tuple element as a separate argument.
It's basically the reverse of the * you might use to capture all non-keyword arguments in a function definition:
def fn(*args):
# args is now a tuple of the non-keyworded arguments
print args
fn(1, 2, 3, 4, 5)
prints (1, 2, 3, 4, 5)
fn(*[1, 2, 3, 4, 5])
does the same.
Try this:
>>> def cord():
... return (1, 1)
...
>>> def printa(y, x):
... print a[y][x]
...
>>> a=[[1,2],[3,4]]
>>> printa(*cord())
4
The star basically says "use the elements of this collection as positional arguments." You can do the same with a dict for keyword arguments using two stars:
>>> a = {'a' : 2, 'b' : 3}
>>> def foo(a, b):
... print a, b
...
>>> foo(**a)
2 3
Actually, Python doesn't really return multiple values, it returns one value which can be multiple values packed into a tuple. Which means that you need to "unpack" the returned value in order to have multiples.
A statement like
x,y = cord()
does that, but directly using the return value as you did in
printa(cord())
doesn't, that's why you need to use the asterisk. Perhaps a nice term for it might be "implicit tuple unpacking" or "tuple unpacking without assignment".

Python convert string to variable name

Im aware that this may come up as a duplicate but so far I haven't found (or should that be understood) an answer to what Im looking for.
I have a list of strings and want to convert each one into a variable name which I then assign something to. I understand that I may need a dict for this but I am unfamiliar with them as I am relatively new to python and all the examples I have seen so far deal with values whilst I'm trying something different.
Im after something like:
list = ['spam', 'eggs', 'ham']
for i in range(len(list)):
list[i] = rat.readColumn(ratDataset, list[i])
where the first list[i] is a variable name and not a string. The second list[i] is a string (and for context is the name of a column Im reading from a raster attribute table (rat))
Essentially I want each string within the list to be set as a variable name.
The idea behind this is that I can create a loop without having to write out the line for each variable I want, with matching rat column name (the string). Maybe there is a beer way of doing this than I am suggesting?
Try the following:
lst = ['spam', 'eggs', 'ham']
d = {} # empty dictionary
for name in lst:
d[name] = rat.readColumn(ratDataset, name)
Do not use list for your identifiers as it is a type identifier and you would mask its existence. The for loop can iterate directly for the elements inside -- no need to construct index and use it aganist the list. The d['spam'] will be one of your variables.
Although, it is also possible to create the real variable names like spam, eggs, ham, you would not probably do that as the effect would be useless.
Here comes a simple dictionary use :
variables = ['spam', 'eggs', 'ham']
data = {}
datum = 0
for variable in variables:
data[variable] = datum
datum+=1
print(data)
print("value : ",data[variables[2]])
It gives as result :
{'eggs': 1, 'ham': 2, 'spam': 0}
value : 2
NB : don't use list as a variable name, list is a type identifier that you can use to transform an object into a list if possible (list("abc")==['a', 'b', 'c']) and you are overriding it with your value list right now.
one way is setting the variable name as a string and changing a part or all of it via format() method and then using the string as a varibale via vars()[STRING]
import numpy as np
X1= np.arange(1,10)
y1=[i**2 for i in X1]
X2= np.arange(-5,5)
y2=[i**2 for i in X2]
for i in range(1,3):
X = 'X{}'.format(i)
y = 'y{}'.format(i)
print('X_{}'.format(i) , vars()[X])
print('y_{}'.format(i) , vars()[y])
Output:
X_1 [1 2 3 4 5 6 7 8 9]
y_1 [1, 4, 9, 16, 25, 36, 49, 64, 81]
X_2 [-5 -4 -3 -2 -1 0 1 2 3 4]
y_2 [25, 16, 9, 4, 1, 0, 1, 4, 9, 16]

Resources