If you want the effect of a nested for loop, use:
import itertools
for i, j in itertools.product(range(x), range(y)):
# Stuff...
If you just want to loop simultaneously, use:
for i, j in zip(range(x), range(y)):
# Stuff...
Note that if x and y are not the same length, zip will truncate to the shortest list. As @abarnert pointed out, if you don't want to truncate to the shortest list, you could use itertools.zip_longest.
UPDATE
Based on the request for "a function that will read lists "t1" and "t2" and return all elements that are identical", I don't think the OP wants zip or product. I think they want a set:
def equal_elements(t1, t2):
return list(set(t1).intersection(set(t2)))
# You could also do
# return list(set(t1) & set(t2))
The intersection method of a set will return all the elements common to it and another set (Note that if your lists contains other lists, you might want to convert the inner lists to tuples first so that they are hashable; otherwise the call to set will fail.). The list function then turns the set back into a list.
UPDATE 2
OR, the OP might want elements that are identical in the same position in the lists. In this case, zip would be most appropriate, and the fact that it truncates to the shortest list is what you would want (since it is impossible for there to be the same element at index 9 when one of the lists is only 5 elements long). If that is what you want, go with this:
def equal_elements(t1, t2):
return [x for x, y in zip(t1, t2) if x == y]
This will return a list containing only the elements that are the same and in the same position in the lists.
Answer from SethMMorton on Stack Overflow
I'm a Python beginner and wondering if anyone can explain what the for j in range i line is doing here? In addition, what is the proper name for these i and j expressions?
n=5;
for i in range(n):
for j in range(i):
print ('* ', end="")
print('')
for i in range(n,0,-1):
for j in range(i):
print('* ', end="")
print('')If you want the effect of a nested for loop, use:
import itertools
for i, j in itertools.product(range(x), range(y)):
# Stuff...
If you just want to loop simultaneously, use:
for i, j in zip(range(x), range(y)):
# Stuff...
Note that if x and y are not the same length, zip will truncate to the shortest list. As @abarnert pointed out, if you don't want to truncate to the shortest list, you could use itertools.zip_longest.
UPDATE
Based on the request for "a function that will read lists "t1" and "t2" and return all elements that are identical", I don't think the OP wants zip or product. I think they want a set:
def equal_elements(t1, t2):
return list(set(t1).intersection(set(t2)))
# You could also do
# return list(set(t1) & set(t2))
The intersection method of a set will return all the elements common to it and another set (Note that if your lists contains other lists, you might want to convert the inner lists to tuples first so that they are hashable; otherwise the call to set will fail.). The list function then turns the set back into a list.
UPDATE 2
OR, the OP might want elements that are identical in the same position in the lists. In this case, zip would be most appropriate, and the fact that it truncates to the shortest list is what you would want (since it is impossible for there to be the same element at index 9 when one of the lists is only 5 elements long). If that is what you want, go with this:
def equal_elements(t1, t2):
return [x for x, y in zip(t1, t2) if x == y]
This will return a list containing only the elements that are the same and in the same position in the lists.
There's two possible questions here: how can you iterate over those variables simultaneously, or how can you loop over their combination.
Fortunately, there's simple answers to both. First case, you want to use zip.
x = [1, 2, 3]
y = [4, 5, 6]
for i, j in zip(x, y):
print(str(i) + " / " + str(j))
will output
1 / 4
2 / 5
3 / 6
Remember that you can put any iterable in zip, so you could just as easily write your exmple like:
for i, j in zip(range(x), range(y)):
# do work here.
Actually, just realised that won't work. It would only iterate until the smaller range ran out. In which case, it sounds like you want to iterate over the combination of loops.
In the other case, you just want a nested loop.
for i in x:
for j in y:
print(str(i) + " / " + str(j))
gives you
1 / 4
1 / 5
1 / 6
2 / 4
2 / 5
...
You can also do this as a list comprehension.
[str(i) + " / " + str(j) for i in range(x) for j in range(y)]
for loop - python newbie: for j in range - Stack Overflow
"for i in range()" to do an infinite loop with a counter - Ideas - Discussions on Python.org
understanding range in python for loop - Stack Overflow
What does "for i in range" mean in Python?
Videos
I think @csevier added a reasonable discussion about your first question, but I'm not sure the second question is answered as clearly for you based on your comments so I'm going to try a different angle.
Let's say you did:
Copyfor x in range(10):
print(x)
That's reasonably understandable - you created a list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] and you printed each of the values in that list in-turn. Now let's say that we wanted to just print "hello" 10 times; well we could modify our existing code very simply:
Copyfor x in range(10):
print(x)
print('hello')
Umm, but now the x is messing up our output. There isn't a:
Copydo this 10 times:
print('hello')
syntax. We could use a while loop but that means defining an extra counter:
Copyloop_count = 0
while loop_count < 10:
print('hello')
loop_count += 1
That's baggage. So, the better way would be just to use for x in range(10): and just not bother doing print(x); the value is there to make our loop work, not because it's actually useful in any other way. This is the same for j (though I've used x in my examples because I think you're more likely to encounter it in tutorials, but you could use almost any name you want). Also, while loops are generally used for loops that can run indefinitely, not for iterating over an object with fixed size: see here.
Welcome to the python community! This is a great question. In python, as in other languages, there are many ways to do things. But when you follow a convention that the python community does, that is often referred to as a "pythonic" solution. The method print_progression is a common pythonic solution to iteration of a user defined data structure. In the case above, lets explain first how the code works and then why we would do it that way.
Your print_progression method takes advantage of the fact that your Progression class implements the iteration protocol by implementing the next and iter dunder/magic methods. Because those are implemented you can iterate your class instance both internally as next(self) has done, and externally next(Progression()) which is the exactly what you were getting at with you number 1. Because this protocol is implemented already, this class can by used in any builtin iterator and generator context for any client! Thats a polymorphic solution. Its just used internally as well because you don't need to do it in 2 different ways.
Now for the unused J variable. They are just using that so they can use the for loop. Just using range(n) would just return an itterable but not iterate over it. I dont quite agree with the authors use of the variable named J, its often more common to denote an unused variable that is just used because it needs to be as a single underscore. I like this a little better:
Copy print(' '.join(str(next(self)) for _ in range(n)))
See the docs:
range([start], stop[, step])
When comparing it to a for(..; ..; ..) loop e.g. in C the three arguments are used like this:
for(int i = start; i != stop; i += step)
There are also good examples in the docs:
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(0, -10, -1)
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]
For range(), the basic idea is that it generates a sequence of items for you. See this as reference http://docs.python.org/library/functions.html#range :
format: range([start], stop[, step])
In the meantime here is some basic explanation, easiest example:
range(5)
will generate numbers in the range starting at 0 (default start value) and go up to but not including 5, by increments of 1 (default value), so
In [1]: range(5)
Out[1]: [0, 1, 2, 3, 4]
You can specify additional parameters to range, such as the starting value, the ending value and also the stepvalue. So range(startval, endval, stepval). Notice that endval is not included in the sequence that is generated.
range(0, 5, 1)
is equivalent to
range(5)
To generate all even numbers between 0 and 20 you could do for instance
range(0, 21, 2)
Note that prior to Python 3 range generates a list and xrange generates the number sequence on demand.
In your specific code are using list comprehensions and range. It might be easier to understand the algorithm and the role of the for loops with range by eliminating the list comprehension temporarily to get a clearer idea. List comprehension is a powerful and efficient construct and should definitely be used if you plan on keeping the original code though.
#noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
noprimes = []
for i in range (2, 8):
for j in range (i*2, 50, i):
noprimes.append(j)
# primes = [x for x in range(2, 50) if x not in noprimes]
primes = []
for x in range(2, 50):
if x not in noprimes:
primes.append(x)
So, I had a question where I was supposed to find the sum of the first natural numbers using Python.
Here's the problem:
Write a program to find the sum of the cubes of the first n natural numbers, where the value of n is provided by the user.
And this is the code that my professor used to allow the interpreter to produce the result:
= int(input("Enter a number:"))
sum = 0
for i in range (n+1): sum = sum + i*i*i
# for i in range starts as a loop, and then tries to get to (n + 1), whatever that may be
print("the sum of the first", n, "integers is", sum)
However, I can't seem to understand what "for i in range (n + 1): sum = sum + i * i * i" means. In other words, I don't understand what role this part of the code is doing to produce the result. Especially, I don't understand what the role of "for i in range (n + 1)" is doing. Does anyone mind explaining this to me?