Assigning values to variables in a list using a loop
Python variables are names for values. They don't really "contain" the values.
for var in var_list:
causes var
to become a name for each element of the list, in turn. Inside the loop, var = num
does not affect the list: instead, it causes var
to cease to be a name for the list element, and instead start being a name for whatever num
currently names.
Similarly, when you create the list, if one
, two
and three
aren't already names for values, then you can't use them like that, because you are asking to create a list of the values that have those names (and then cause var_list
to be a name for that list). Note that the list doesn't really contain the values, either: it references, i.e. shares them.
Variable assignment within a for-loop
Assignment works like this:
<varname> = <expression>
or more traditionally
<varname> <- <expression>
So, in your code, you have only ever assigned to varName
. It's not about assignment vs equality, just assignment. You may want to look at assign
:
for (i in 1:5) {
assign(paste0("Variable", i), 10*i)
}
as a toy example.
Moreover, as noted in the comments, there are probably better approaches for your application. For example, why not just use a vector myvector
and instead of having variables called Variable1
, Variable2
, etc you can refer to myvector[1]
, myvector[2]
etc.
As an example, let us say you had planned to work with
Variable1 <- 'foo'
Variable2 <- 'bar'
Variable3 <- 'baz'
then, you could change you approach, and set
mydata <- c('foo', 'bar', 'baz')
and where you would previously have used Variable2
(which contains 'bar'
) you instead use mydata[2]
(which also contains 'bar'
). The point here is that it is much easier to work with vectors and dataframes in R than a long list of variables.
You could go further and name the entries:
names(mydata) <- paste0("V", 1:3)
which then allows you to write mydata["V2"]
to retrieve bar
.
Variable assignment inside for in loop
The simple answer is: NO.
Python uses a mechanism, which is known as "Call-by-Object", sometimes also called "Call by Object Reference" or "Call by Sharing" when pass function parameters.
If you pass immutable arguments like integers, strings or tuples to a function, the passing acts like call-by-value. The object reference is passed to the function parameters. They can't be changed within the function, because they can't be changed at all, i.e. they are immutable. It's different, if we pass mutable arguments. They are also passed by object reference, but they can be changed in place within the function.
So, after your iterate the list, the value (1.231 +2.254j)
would be a immutable argument which your change won't affect the outside variable. But if you pass the value like [1.231 +2.254j]
to function, then it will make effect like next:
test.py:
myList2 = [[(1.231 +2.254j)], [(2.875 +23.543j)]]
print(myList2)
def round_complex(x, digits):
return complex(round(x.real, digits), round(x.imag, digits))
for item2 in myList2:
item2[0] = round_complex(item2[0], 2)
print(myList2)
Execution:
$ python3 test.py
[[(1.231+2.254j)], [(2.875+23.543j)]]
[[(1.23+2.25j)], [(2.88+23.54j)]]
In a word, for you scenario, if you insist organize your input data as that & iterate with that way, you can't change the outside value directly inside the function.
You may refers to this to learn more.
How to assign a variable for each item of the loop
Use an array
const dataArr = [];
for (var i = 0; i < dataForecast.list.length; i += 8) {
const data = dataForecast.list[i].dt_txt;
dataArr.push(data);
}
console.log(dataArr); // access the array
How to assign a variable in inline for loop?
A trick I use sometimes is:
[{'num': per.num, 'name': per.name, 'age': per.age}
for person in mylist for per in [person.information]]
Note that this won't work with the initialization code you provided, as they are simple dict
objects (no dot accessor). But if person.information
was a class
or a namedtuple
, for example, then you could use it as is.
Note about performance
If you worry about that "fake loop" (the one that iterates over a 1-element list), it is interesting to observe what Python does by inspecting the disassembled code. Here is a toy example:
import dis
def f0(mylist):
return [
p['foo']['a']
for p in mylist
]
def f1(mylist):
return [
d['a']
for p in mylist
for d in [p['foo']]
]
Now compare the output of:
>>> dis.dis(f0)
2 0 LOAD_CONST 1 (<code object <listcomp> at 0x7fc886f6d710, file "<ipython-input-28-ebf24f3417d6>", line 2>)
2 LOAD_CONST 2 ('f0.<locals>.<listcomp>')
4 MAKE_FUNCTION 0
4 6 LOAD_FAST 0 (mylist)
2 8 GET_ITER
10 CALL_FUNCTION 1
12 RETURN_VALUE
Disassembly of <code object <listcomp> at 0x7fc886f6d710, file "<ipython-input-28-ebf24f3417d6>", line 2>:
2 0 BUILD_LIST 0
2 LOAD_FAST 0 (.0)
>> 4 FOR_ITER 16 (to 22)
4 6 STORE_FAST 1 (p)
3 8 LOAD_FAST 1 (p)
10 LOAD_CONST 0 ('foo')
12 BINARY_SUBSCR
14 LOAD_CONST 1 ('a')
16 BINARY_SUBSCR
18 LIST_APPEND 2
20 JUMP_ABSOLUTE 4
>> 22 RETURN_VALUE
with that of f1
:
>>> dis.dis(f1)
2 0 LOAD_CONST 1 (<code object <listcomp> at 0x7fc886f6d870, file "<ipython-input-29-73fac11e7b55>", line 2>)
2 LOAD_CONST 2 ('f1.<locals>.<listcomp>')
4 MAKE_FUNCTION 0
4 6 LOAD_FAST 0 (mylist)
2 8 GET_ITER
10 CALL_FUNCTION 1
12 RETURN_VALUE
Disassembly of <code object <listcomp> at 0x7fc886f6d870, file "<ipython-input-29-73fac11e7b55>", line 2>:
2 0 BUILD_LIST 0
2 LOAD_FAST 0 (.0)
>> 4 FOR_ITER 28 (to 34)
4 6 STORE_FAST 1 (p)
5 8 LOAD_FAST 1 (p)
10 LOAD_CONST 0 ('foo')
12 BINARY_SUBSCR
14 BUILD_TUPLE 1
16 GET_ITER
>> 18 FOR_ITER 12 (to 32)
20 STORE_FAST 2 (d)
3 22 LOAD_FAST 2 (d)
24 LOAD_CONST 1 ('a')
26 BINARY_SUBSCR
28 LIST_APPEND 3
30 JUMP_ABSOLUTE 18
>> 32 JUMP_ABSOLUTE 4
>> 34 RETURN_VALUE
As you can see, the code for f1
has only one BUILD_LIST
(like f0
). There is however a BUILD_TUPLE
of a single element (p['foo']
), a GET_ITER
for that tuple and a FOR_ITER
. These operations are all extremely fast, using builtin and fixed-sized objects.
How to assign variables in a for loop in Python
because var is not appending anything it's just overwriting the value in Var but there isn't much point in appending it to separate lists as its all in one list already and everything is accessible by using
records[X][Y]
with X being the sublist location and Y being the value inside that sublist
and if you want this to be easier to use i'll suggest using dictionaries but this isn't necessary
How do I assign to a variable in a for loop in C?
It looks as if you've carefully coded it to create zero warnings even though it is very wrong, with all sorts of array of strings, and pointers to characters being flown around.
You want to have a single string of 2 characters, for that an array of 3 characters is sufficient:
char temp[3];
temp[2] = '\0';
...
temp[0] = word[i];
temp[1] = word[j];
puts(temp); // less typing but essentially the same as printf("%s\n", temp);
For loop to assign value to variable based on value of another var
You can use np.where
to assign values to 'My_new_status'
:
df['My_new_status'] = np.where(df['Housing_ID']==1,'valid','')
Output:
Housing_ID Member_ID My_new_status
0 1 1 valid
1 1 2 valid
2 1 3 valid
3 1 4 valid
4 1 5 valid
5 2 1
6 2 2
7 3 1
8 3 2
9 3 3
Assignments in for loops
You can maintain a dictionary, where the keys are strings (the names variables that you originally had) and the values are the integers that they're assigned to.
Then, you can do the following:
data = {
"p": 1,
"q": 2,
"r": 3
}
for item in data:
data[item] += 1
print(data)
This outputs:
{'p': 2, 'q': 3, 'r': 4}
Problem with value assignment inside a for loop
This assignment statement
unsorted_rs[i] = unsorted_array[i];
invokes undefined behavior because there is an attempt to access memory beyond the array unsorted_rs
when the value of the index i
is greater than or equal to ls_len
.
You should write
unsorted_rs[i - ls_len] = unsorted_array[i];
Pay attention to that instead of this if-else statement
if (size_of_arr % 2 == 0) // if lenght of an array is even then lenght of each half equals: lenght of arr / 2
{
ls_len = size_of_arr / 2;
rs_len = size_of_arr / 2;
}
else // else lenght of arr / 2 and right half++
{
ls_len = size_of_arr / 2;
rs_len = size_of_arr / 2 + 1;
}
you could just write
ls_len = size_of_arr / 2;
rs_len = size_of_arr - ls_len;
Related Topics
Calling Library() in R with a Variable as the Argument
What Is the Internal Implementation of Lists
R Crashing While Displaying Ggplot After Update (Process Memory Read Out of Range)
Package 'Pbkrtest' Is Not Available (For R Version 3.2.2)
Testthat Fails Within Devtools::Check But Works in Devtools::Test
If Column Contains String Then Enter Value for That Row
Constructing a Named List Without Having to Type Each Object's Name Twice
R Get Last Element from Str_Split
Rcurl: Http Authentication When Site Responds with Http 401 Code Without Www-Authenticate
R: Saving Ggplot2 Plots in a List
Accessing Element of a Split String in R
Converting a "Map" Object to a "Spatialpolygon" Object