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.
Related
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]
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 an idea but don't know how to execute it.
i have a variable value EG: 5
now i want my python program to create 5 different list all with differnt names
EG: list1 = []
list2 = []
...
I don't know if this is possible. When you say list1, you mean that list1 is an identifier for a variable which is a list. I don't think it is possible that the program creates identifiers within itself (or at least I don't know how).
Of course, you can write a Python program which writes another Python program where there are variables with these identifiers, then get creative with it:
VAL = 5 # can change this
f = open("lists.py", "w")
for i in range(1, VAL + 1):
f.write("list" + str(i) + " = []\n")
f.close()
Output (lists.py):
list1 = []
list2 = []
list3 = []
list4 = []
list5 = []
Morning Jacob,
I have a little bit of difficulties reading your question. But let me try to answer your question.
Direct answer
There are no simple way to generate python variables. The only way I know is to generate the code as str and then execute it.
def generate_code(n):
ret = ""
for i in range(1, n + 1):
var_name = "lst_" + str(i)
ret += var_name + " = []\n"
return ret
code = generate_code(5)
print(code)
exec(code)
where the printed code will be
lst_1 = []
lst_2 = []
lst_3 = []
lst_4 = []
lst_5 = []
The idiomatic solution
The idiomatic solution would be to create a list of list. Something like bellow.
lsts = [[] for i in range(5)]
then, you could access your sub lists using indexes in a very similar fashion then with the variables you asked for. lsts[0] would be equivalent of the above lst_1, lsts[1] would be equivalent of the above lst_2, lsts[2] would be equivalent of the above lst_3, ...
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 have a for loop where I count in i in range(0, 999999999) and I want to add these in a set with a second variable, for example (pseudo code):
import random
the_set = set()
for i in range(0, 999999999):
x = random.randint(0,100)
the_set.append(str(i)+":"+str(x))
i and x are example variables where in this case the elements in the set are always unique, I understand that, but with the actual variables non-uniques may occur but shouldn't be in the set.
How do I define such a set and .append() values?
Python set doesn't have append method, but they have add. So, you can do
the_set.add(str(i)+":"+str(x))
In this case, you can simply use set comprehension, like this
the_set = {"{}:{}".format(i, random.randint(0,100)) for i in range(999999999)}
But the actual problem here is 999999999. It is a very big number. So, its not advisable to build a set of that size and holding it in memory. If you are just going to use this as a unique number generator, you can simply use a generator, like this
def get_next_number(max_number):
for i in xrange(max_number): # use `range` if you are using Python 3.x
yield "{}:{}".format(i, random.randint(0,100))
And then you can use it in a loop like this
for new_number in get_next_number(999999999):
print new_number
If I understand correctly, your goal is to ignore x if it has already been generated, I think you might want to use a dictionary instead:
the_dict()
for i in range(0, 999999999):
x = random.randint(0,100)
if the_dict.has_key(x):
continue
the_dict[x] = i
you could build the resulting set afterward:
the_set = {'%i:%i' % (value, key) for key, value in the_dict.iteritems()}
the_set = {'{}:{}'.format(i, random.randint(0,100)) for i in xrange(10)}