I am new to Python and I am trying to create multiple variables with the values of zero.
var1 = 0
var2 = 0
var3 = 0
so on...
How to do this in Python
You could use a list to store your values like this:
l = []
for i in range(10):
l.append(0)
It would work like this (almost what #CoolCoding123 has)
var1,var2, var3 = (0, 0, 0)
You almost never need to do this, i.e. create variables dynamically. But you could do it by altering the global variable dictionary. The below would create variables var0...var9 with every one set to 0:
varnames = ['var' + str(n) for n in range(10)]
for var in varnames:
globals()[var] = 0
However, don't do such evil things. Read up on data structures such as list and dicts.
As you asked how to create multiple variables with zero values, here is one way to do:
n = 5
data = {}
for i in range(5):
data["var%s" % i] = 0
Later on, if you need the value of a particular index i, then you can get the value using
value = data["var%s" % index]
Related
I need to have different results for different "i"s
so whenever i call for example a_8, it should return me the exact value. but python
doesnt assign diferrent "i"s to it and just knows a_i.
1.for i in range(10): a_i = i + 5
You can use a list:
a = []
for i in range(10): a.append(i+5)
or a dictionary:
a = {}
for i in range(10): a[i] = i+5
In both cases, you can access the value later with
for i in range(10): print(a[i])
What I should use on my case?
Take a look at this answer.
for i in range(10):
globals()['a_' + str(i)] = i + 5
print(a_6)
but i don't think you should use it, better use dicts instead.
I want to change the a variable from 1 to 50 and create an array from the results so that I can feed it into a curve.
The variable is outside the function but the variable changes a value in the function, that is what I need to make a list of.
a=1
def test(foo):
p =a+2
print(p)
test(foo)
I want to get the p values when I change a from 1 to 50:
[3,4,5,6,7,8,9...]
Not sure what you trying to do but if you need a list of numbers with some starting point, you can simply generate them using list comprehension as:
a = 2
x = [i+a for i in range(1, 50)]
print(x)
EDIT: Based on comments from author.
You need to change print to return the generated number. Also, need to add a loop and a list to generate a new number and keep appending the new number to the list.
Note: As said earlier, it is recommended to use Python's supported features like list comprehension as is shown in the original code.
a = 1
def test(i):
p = a + i
return p
res = []
for i in range(2, 50):
res.append(test(i))
print(res)
I have a 'for' loop where I need t iterate through a list but do not need the iterative variable named 'node'. What would be a more elegant way to do this?
for node in NODES:
if i % 2 == 0:
tex_pairs_to_swap_dict[NODES[i]] = NODES[i+1]
i += 1
Looks like this is a case of actually needing the index in NODES. You get this using range(len(NODES)) but range() also supports an optional parameter of step that would allow you step through this 2 at a time (note: you also have to include the start if you want the step):
for i in range(0, len(NODES), 2):
tex_pairs_to_swap_dict[NODES[i]] = NODES[i+1]
This assumes there is an even number of entries in the list and will raise an IndexError if it isn't.
Alternatively, if all you are trying to do is step through the list 2 at a time you could also use:
it = iter(NODES)
for k, v in zip(it, it):
tex_pairs_to_swap_dict[k] = v
This is equivalent to the above without creating the it variable:
for k, v in zip(*[iter(NODES)]*2):
tex_pairs_to_swap_dict[k] = v
This will silently ignore the last value in an odd sized list.
The most effective way to do this would be to use a range. I would recommend you do this:
for i in range(len(NODES)):
if i % 2 == 0:
tex_pairs_to_swap_dict[NODES[i]] = NODES[i+1]
You can use the enumerate function, which returns a tuple with the index and the item.
for i, _ in enumerate(NODES):
if i % 2 == 0:
tex_pairs_to_swap_dict[NODES[i]] = NODES[i+1]
In python you can define a for loop without a variable and still access the contents of that. For example:
x = [1,2,3]
for _ in x: print (_)
will provide you an output of:
1
2
3
You can also do this with dictionaries. For example:
x = {1:10, 2:20}
for _,__ in x.items(): print (_,__)
The output of this will be:
1 10
2 20
In summary, you can use _ as a variable and reference it. While you may think there is no variable defined, it is still a throwaway variable. More details about _ can be found in this post: What is the purpose of the single underscore "_" variable in Python?
Based on this, you can rewrite your code as follows:
for _ in NODES:
if i % 2 == 0:
tex_pairs_to_swap_dict[NODES[i]] = NODES[i+1]
i += 1
With this, you don't need to use the variable node
I want to create a loop that creates an object if a certain condition is met and then adding it to a list. However, I am unsure how to uniquely name these objects so they can be used/referenced later on. For example something like this:
favNumbers = []
numbers = [6, 21, 5, 22]
class favNumber(object):
def __init__(self, value):
self.value = value
for i in numbers:
if i % 2 == 0:
unique_name_for_object = favNumber(i)
favNumbers.append(unique_name_for_object)
How would I gave the favNumber objects a unique name?
I was thinking of somehow naming them number1, number2, number3... but I think dynamically naming them would be a bad idea.
Is there a way of doing it without dynamically naming them? It seems as if that would be impossible but I am unsure as to how else I could accomplish it.
There is no need to name the instances. Just try this one
favNumbers = []
numbers = [6, 21, 5, 22]
class favNumber(object):
def __init__(self, value):
self.value = value
for i in numbers:
if i % 2 == 0:
favNumbers.append( favNumber(i) )
Now, favNumbers is a list of all created instances. If you want to get the value ot the each instance, just type
for fn in favNumbers:
print(fn.value)
If you simply want to generate a list, you can use a list comprehension:
favNumbers = [favNumber(i) for i in numbers if n % 2 == 0]
The last expression (if n % n == 0) acts as a filter. To access the values, you use an index (eg. favNumbers[0] for the first item), or loop through the list like you did with numbers.
As someone pointed out in the comments, {} is a dict and cannot be appended to. You can however insert items given a key (which might as well be the integer i, although it usually makes more sense to use lists when the keys are consecutive non-negative integers).
for i in numbers:
if n % 2 == 0:
favNumbers[i] = favNumber(i)
It can also be done with a dictionary comprehension:
favNumbers = { i : favNumber(i) for i in numbers if n % n == 0 }
I'll update the answer if you provide additional context.
In pseudocode, you can create variables such as 'variable(x)', having x as a forever changing number therefore creating multiple different variables. For example, if:
x = 0
variable(x) = 4
x = 1
variable(x) = 7
then printing 'variable(0)' would give you the result '4' and printing 'variable(1)' would output '7'. My question is: is this possible to do in Python?
You can't use exactly that syntax in Python, but you can come close using a dict.
variable = {}
x = 0
variable[x] = 4
x = 1
variable[x] = 7
print(variable[0])
print(variable[1])
If the domain of your variable is non-negative integers, and you know the largest integer a priori, then you could use a list:
variable = [None]*2
x = 0
variable[x] = 4
x = 1
variable[x] = 7
print(variable[0])
print(variable[1])
The nearest could be a list:
x = []
x.append(4)
x.append(7)
print(x[0])
4
print(x[1])
7
And if you don't want to use a count as identifier you can use Rob's answer.
you can use dictionary
variable = {}
variable['0'] = 4
variable['1'] = 7
x=1
print varibale[x]
will print 7
Seeing as your pseudocode doesn't declare a variable, but a function, it's pretty easy to build something like this:
def my_function(x):
return 3*x + 4
Then you can
print my_function(0)
4
print my_function(1)
7
Of course, you can do pretty much everything in that function; the mathematical linear mapping I used was just an example. You could be reading a whole file, looking for x in it and returning e.g. the line number, you could be tracking satellite positions and return the current position of satellite Nr. x... This is python, a fully-fledged programming language that supports functions, like pretty much every non-declarative programming language I can think of.