I want to write a for loop that iterates over variables and updates their values.
for example:
x = 1
y = 1
for varNames in [x,y]:
varNames = varNames + 1
print(x)
print(y)
Here I want to have the function print the value 2 for both x and y, but my output is still 1. It is because the varNames variable gets updated but not x and y. How do I update the values for actual variable names x and y?
Thanks for the help!
At the global level (i.e. not within a function) you could do this using the globals() function.
x = 1
y = 1
for varName in ["x","y"]:
globals()[varName] += 1
print(x) # 2
print(y) # 2
However, if you need to do that kind of thing in your program, you might want to learn more about lists and dictionaries which would be the preferred approach.
data = dict()
data["x"] = 1
data["y"] = 1
for varName in data:
data[varName] = data[varName] + 1
print(data["x"]) # 2
print(data["y"]) # 2
You can just make a list containing the variables and then you can iterate over them and print each object of the list.
x = 1
y = 3
mylist=[x,y]
for index in mylist:
print(index)
Related
I have an object x
print(x)
1
1
2
print(type(x).__name__)
int
int
int
How do I extract only the first 1 from it. If I try x[0], I get the following message
TypeError: 'int' object is not subscriptable
I found a lot of questions about the error but none of the solutions worked for me.
Here is the stdin from where x was read
3
1 2 3
1 3 2
2 1 3
Here is how it was read
q = int(input().strip())
for a0 in range(q):
x,y,z = input().strip().split(' ')
x,y,z = [int(x),int(y),int(z)]
Typically you store them in a container (for example a list) during the loop in case you want to access them later on.
For example:
q = int(input().strip())
res = []
for a0 in range(q):
x,y,z = input().strip().split(' ')
res.append([int(x),int(y),int(z)])
print(res) # all x, y and z
or to access specific elements:
print(res[0][0]) # first x
print(res[1][0]) # second x
print(res[0][1]) # first y
Below is the code(I know below code is wrong syntax just sharing for understanding requirement) I am using to test multiple for loop.
server = ['1']
start = 2
end = 4
for x in range(start, end + 1) and for y in serverip:
print x
print y
Requirement.
for loop iterations must not cross server list length or range .
Input 1
start = 2
end = 4
server list length = 1 that is server = ['1']
expected output 1:
print
x = 2
y = 1
Input 2
start = 2
end = 4
server list length = 2 that is server = ['1','2']
expected output 2:
print
x = 2
y = 1
x = 3
y = 2
Input 3
start = 1
end = 1
server list length = 2 that is server = ['1','2']
expected output 3:
print
x = 1
y = 1
Please help.
The easiest way is to use the built-in zip function suggested in the comments. zip creates a list, or an iterator in python 3, with the iterators “zipped” together. Until one of the iterators runs out.
server = ['1']
start = 2
end = 4
for x, y in zip(range(start, end + 1), server):
print x
print y
Output:
2
1
https://docs.python.org/2/library/functions.html#zip :
This function returns a list of tuples, where the i-th tuple contains
the i-th element from each of the argument sequences or iterables. The
returned list is truncated in length to the length of the shortest
argument sequence.
How can I do the following in python;
for i in range(4):
s_i = 3
so I get
s_0 = 3
s_1 = 3
s_2 = 3
s_3 = 3
Keep data out of your variable names. If you want numbered variables, you really need a list:
s = [3] * 4
Then you can access elements with indexing notation:
s[2] = 5
instead of trying to build variable names dynamically.
If you want more general dynamically-named variables, like variables whose names come from user input, you really need a dict:
parents = {}
for i in xrange(5):
child = raw_input('Enter child name:')
parent = raw_input('Enter parent name:')
parents[child] = parent
While the following works, it seems like a very, very bad idea:
>>> for j in range(4):
... globals()['s_{}'.format(j)] = 3
...
>>> s_0
3
>>> s_1
3
>>> s_2
3
>>> s_3
3
EDIT Replaced locals() with globals(). According to the docs for locals():
The contents of this dictionary should not be modified; changes may
not affect the values of local and free variables used by the
interpreter.
I didn't get your question exactly. But I have tried this:
for i in range(4):
exec('s_'+str(i) + '=i')
Out Put :
s_0 = 0
s_1 = 1
s_2 = 2
s_3 = 3
on the fly we are creating 4 variables and assigning values to it.
I've got a list and i've managed to turn the list into strings. Now I want to assign a variable to each item in the list by using string formatting to append a 1 onto the end of the variable.
listOne = ['33.325556', '59.8149016457', '51.1289412359']
itemsInListOne = int(len(listOne))
num = 4
varIncrement = 0
while itemsInListOne < num:
for i in listOne:
print a = ('%dfinalCoords{0}') % (varIncrement+1)
print (str(listOne).strip('[]'))
break
I get the following error: SyntaxError: invalid syntax
How can I fix this and assign a new variable in the format:
a0 = 33.325556
a1 = 59.8149016457 etc.
Your current code has a few issues:
listOne = ['33.325556', '59.8149016457', '51.1289412359']
itemsInListOne = int(len(listOne)) # len will always be an int
num = 4 # magic number - why 4?
varIncrement = 0
while itemsInListOne < num: # why test, given the break?
for i in listOne:
print a = ('%dfinalCoords{0}') % (varIncrement+1) # see below
print (str(listOne).strip('[]')) # prints list once for each item in list
break # why break on first iteration
One line in particular is giving you trouble:
print a = ('%dfinalCoords{0}') % (varIncrement+1)
This:
simultaneously tries to print and assign a = (hence the SyntaxError);
mixes two different types of string formatting ('%d' and '{0}'); and
never actually increments varIncrement, so you will always get '1finalCoords{0}' anyway.
I would suggest the following:
listOne = ['33.325556', '59.8149016457', '51.1289412359']
a = list(map(float, listOne)) # convert to actual floats
You can easily access or edit individual values by index, e.g.
# edit one value
a[0] = 33.34
# print all values
for coord in a:
print(coord)
# double every value
for index, coord in enumerate(a):
a[index] = coord * 2
Looking at your previous question, it seems that you probably want pairs of coordinates from two lists, which can also be done with a simple list of 2-tuples:
listOne = ['33.325556', '59.8149016457', '51.1289412359']
listTwo = ['2.5929778', '1.57945488999', '8.57262235411']
coord_pairs = zip(map(float, listOne), map(float, listTwo))
Which gives:
coord_pairs == [(33.325556, 2.5929778),
(59.8149016457, 1.57945488999),
(51.1289412359, 8.57262235411)]
I need to change the values of a Ordered Dictionary. I used a for loop but the values weren't changing. I discovered this was because I was assigning to the variable name in the loop rather than directly with the bracket [] notation. Why can't I refer to the values in the loop by the loop variable name?
Tried:
idx = 0
for name,val in settings.items():
idx += 1
val = idx
print name,val
Result: OrderedDict([('Accel X Bias', None), ('Mag X Bias', None)])
Expected: OrderedDict([('Accel X Bias', 1), ('Mag X Bias', 2)])
Full code:
import collections
settings = collections.OrderedDict([('Accel X Bias', None), ('Mag X Bias', None)])
idx = 0
print "\nIn loop, values are changed:"
for name,val in settings.items():
idx += 1
val = idx
print name,val
print "\nAfter Loop, values didn't change:\n",settings
for name,val in settings.items():
idx += 1
val = idx
settings[name] = idx
print "\nAfter Loop, bracket notation used, values changed successfully:\n",settings
This is probably some basic programming principle so I'm interested in 'why' so I don't make more mistakes like these. Thanks!
Variable names in Python are references that "point to" values. Here's how that looks before you try val = idx:
And here's what it looks like after:
If you did settings['Accel X Bias'] = idx instead, you'd get:
In the loop, name and val are bound to each of the objects in the mapping in turn. Simply rebinding the names will not modify the original iterable.