query on Python list comprehension [duplicate] - python-3.x

This question already has answers here:
Modify a list while iterating [duplicate]
(4 answers)
Can't modify list elements in a loop [duplicate]
(5 answers)
Closed 4 years ago.
I tried:
a = [0,1, 2, 3, 4, 5]
this works fine:
>>> for q in a:
... print(q)
...
0
1
2
3
4
But, if I try to change the (mutable) list objects like so, it doesn't work:
>>> for q in a:
... q = 0
...
>>> a
[0, 1, 2, 3, 4]
It seems to me that each time through the loop, q refers to a[n], as n ranges from 0 to 4. So, it would seem, setting q = 0 ought to make the list all value zero.
Any suggestions that are quite Pythonic?

Updating iterating variable inside loop does not itself update the iterator you iterate through.
for q in a:
q = 0
You are just modifying value of q, but do not touch the original list a.
To make all elements in list to 0, use a list-comprehension:
a = [0 for _ in a]

Related

Iterate through 2 Python list and get all x to y combinations [duplicate]

This question already has answers here:
How to get the cartesian product of multiple lists
(17 answers)
Closed 2 years ago.
I have the following two lists:
x = [1,2]
y = [4,5,6]
I want to iterate x by z.
I have a variable called code set to NONE and another variable called value also set to NONE. Here is the output I am aiming for:
1st iteration, code = 1 and value = 4
2nd iteration, code = 1 and value = 5
3rd iteration, code = 1 and value = 6
4th iteration, code = 2 and value = 4
5th iteration, code = 2 and value = 5
6th iteration, code = 2 and value = 6
Here is what I have tried:
x = [1, 2]
y = [4, 5, 6]
code = None
value = None
for x_ids, y_ids in zip(x, y):
code = x_ids
value = y_ids
print("c", code)
print("v", value)
output:
c 1
v 4
c 2
v 5
Can anyone suggest how to get the output described above?
This is one way to achieve what you're looking for:
x = [1, 2]
y = [4, 5, 6]
code = None
value = None
iter_count = 0
for x_ids in x:
code = x_ids
for y_ids in y:
iter_count += 1
value = y_ids
print('{} iteration, code = {} and value = {}'.format(iter_count, code, value))
#print(str(iter_count) + ' iteration, code = ' + str(code) + 'and value = ' + str(value))
Like discussed in the comments, this code iterates through all elements of y for every element in x. In your original code, you were iterating through both lists all at ones, using zip. Since you want to print the number of iteration too, there is a new variable, iter_count, that counts and stores those.
The code has two print statements, they print the same messages. The commented out one concatenates strings, and numbers converted to strings. The uncommented one may be less intuitive but it is often more useful and cleaner. It's worth looking at it, you can find an introduction here.
Last thing, if you need that too - to print numbers in 1st, 2nd etc. format you can use some of these approaches.

Nested for loop resets iterator even though the iterator is manipulated [duplicate]

This question already has answers here:
Scope of python variable in for loop
(10 answers)
Closed 9 years ago.
I am trying to do something as simple as changing the varible in which I am iterating over (i) but I am getting different behaviours in both Python and C.
In Python,
for i in range(10):
print i,
if i == 2:
i = 4;
I get 0 1 2 3 4 5 6 7 8 9, but the equivalent in C:
int i;
for (i = 0; i < 10; i++) {
printf("%d", i);
if (i == 2)
i = 4;
}
I get 01256789 (note that numbers 3 and 4 don't appear, as expected).
What's happening here?
Python has a few nice things happening in the background of for loops.
For example:
for i in range(10):
will constantly set i to be the next element in the range 0-10 no matter what.
If you want to do the equivalent in python you would do:
i = 0
while i < 10:
print(i)
if i == 2:
i = 4
else: # these line are
i += 1 # the correct way
i += 1 # note that this is wrong if you want 1,2,4,5,6,7,8,9
If you are trying to convert it to C then you have to remember that the i++ in the for loop will always add to the i.
The function range() creates a list.
For example, range(10) will create the following list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].
When you say for i in range(10), first off all the list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] will be generated, and then i will be assigned all the values from that list, in order.
It doesn't matter if you change the value of i because on the next iteration it will be assigned the next element from the list.
It C/C++ on the other hand, at the end of each iteration the value of i is incremented and then compared to the maximum allowed value (in this case 9) and if it is greater, then the loop ends.
When you call range(10) you create an iteratable list [0,1,2,3,4,5,6,7,8,9].
And the for loop just pick up one number after the other from the list at each turn, whether or not you haved changed the value of i.
Python gives you the elements in range(10), one after another. C repeatedly increments a variable.
Both of them don't really care what else you do with the variable inside the loop, but since the two language constructs do slightly different things, the outcome is different in some cases.
You can not do this by using range function.
you have to do it by using while loop only because for loop uses range function and in range function variable will get incremented by its internal method no matter what you specify in the loop it will get incremented by range list only.
for i in range(10):
... print i
... if i == 2:
... i = 4
... else:
... i += 1
...
0
1
2
3
4
5
6
7
8
9
An interesting example is here....
for i in range(10):
... print i
... i = i + 10
... print i
...
this will print...
0
10
1
11
2
12
3
13
4
14
5
15
6
16
7
17
8
18
9
19
It's because when you use the range() function in python. Your variable i will be go through the value in range. For example,
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
However, the C language that you have written is just using the normally condition to change the value of i. There is no function involved.

This for circle cannot delete every same elements in a list, I don't know why [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 4 years ago.
a = [1, 2, 2]
value = 2
for i in a:
if i == value:
a.remove(i)
I want to delete 2 same elements in a list. But the result tells me I just delete one of them. when I debug it, I find it only cycle 2 times, not 3 as I wish.
You can use a simple list comprehension for a 1-line solution:
In [2764]: a = [1, 2, 2]
In [2755]: value = 2
In [2768]: a = [i for i in a if i != value]
In [2769]: a
Out[2769]: [1]
You can write the above as :
ans = []
for i in a:
if i <> value:
ans.append(i)
OR, you can also use filter to remove all occurrences:
Python-2
In [2778]: filter(lambda x: x!= value, a)
Out[2778]: [1]
Python-3
In [5]: list(filter(lambda x: x!= value, a))
Out[5]: [1]
Here you don't have to use a comparison to remove a certain value from list
Here is a little modification to your code:
a = [1, 2, 2]
value = 2
try:
for i in a: a.remove (value)
except ValueError: pass
print (a)
Whenever the remove () function couldn't find the value you are looking for, it will raise a value error: ValueError: list.remove(x): x not in list. To eliminate this, surround it with a try except. That'll do the trick.
However there are more easier methods to use remove () function. For an example you could use while loop.
Look at this code:
a = [1, 2, 2]
value = 2
while value in a:
a.remove (value)
print (a)
Its far more easier.

How to input arrays of numbers in one line(not one input in each line) for a given number of n elements and make a list in Python? [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 4 years ago.
N=5
Input: 12345
Output: [1,2,3,4,5]
No need for map or lambda, you can just use the list() function or list comprehension;
an_array = input()
>>> 12345
print([int(x) for x in an_array])
>>> [1, 2, 3, 4, 5]
Iterate through input string (using For loops) and create array (using List).

Why two different simple list variables behave exactly like each other? [duplicate]

This question already has answers here:
Variable assignment and modification (in python) [duplicate]
(6 answers)
Closed 4 years ago.
Something very strange is happening to me. when i write this code down :
a = [3,2,4]
b = a
a.sort()
print(a)
print(b)
The variable "b" must be [3,2,4] and "a" must be [2,3,4].
But this result came out :
[2, 3, 4]
[2, 3, 4]
Why did it sort both of them?
I think it only happens to lists,because I tried to write the code below :
dots = dotsDetecter(param).getDots()
wholeDots = dots
The variable "dots" is gonna be a list but after that whatever I do to the "dots" list, wholeDots variable changes exactly like dots.
Does anybody now why it is happening?
b = a does not instantiate a new list, b is just an alias of a. So every operation on a will also affect b. You should do something like this:
def main():
a = [3, 2, 4]
b = list(a) # create new list initialized with a values
a.sort()
print(a)
print(b)

Resources