For example:
my_list = [x for x in range(10)]
for i in my_list:
i = 1
print(my_list)
This code will print a list containing numbers between 0 - 9. But I want if I change i
, the actual value in my_list
will change too. So for the example, I want it to print between 1 - 10.
I can do:
my_list = [x for x in range(10)]
for i in range(len(my_list)):
my_list[i] = 1
print(my_list)
but I heard that this kind of for
loop when you use len()
is bad. So is there any other way?
I know that i
is not a reference, but I want to make it like one.
CodePudding user response:
You can use only one list comprehension instead of using two loops:
my_list = [x 1 for x in range(10)]
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
CodePudding user response:
You can use a list comprehension:
my_list = [x 1 for x in range(10)]
# or:
my_list = [x for x in range(10)]
my_list = [x 1 for x in my_list]
In your first loop, i
is just a name, it's not a reference to the list in any way.