Python: nested for loop - python

Hello am a beginner to python and I have been stuck at this problem for awhile now. I want to start with 2 lists:
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list2 = [a, b, c]
And write a function that will give me this output:
a
1
2
3
b
4
5
6
c
7
8
9
I have tried using nested for loops and a counter but I am unsure how to obtain the above result.
counter = 0
for i in list2:
print(i)
for j in list1:
print(j)
counter += 1
if counter == 3:
counter = 0
break
Any help would be appreciated!

Here's one possible way, closer to what you intended to write:
j = 0
for i in list2:
print(i)
for _ in range(3):
print(list1[j])
j += 1

Here's an option:
for i, v1 in enumerate(list2):
print(v1)
for v2 in list1[i*3:(i+1)*3]:
print(v2)
You don't need to make and update your own counters here. The built-in enumerate() function generates a counter for you and automatically updates it for each step of the loop. Then you can use list slicing to get the right three values of the inner list.

Try this:
for i in list2:
print(i)
# here you don't have to take it back to 0
counter = 0
for j in range(len(list1)):
# Use range to loop the list so you can cut it off later
# from the position you reach the third element
print(list1[j])
counter += 1
if counter == 3:
list1 = list1[j + 1:]
break
It outputs what you expect:
a
1
2
3
b
4
5
6
c
7
8
9

Related

Python nested for loop issues

I am trying to use a nested for loop to simply add two sets of numbers together respectively.
x=[1,2,3,4]
f=[0,1,2,3]
for i in x:
for j in f:
ans = i+j
ans2 = j
print(ans,ans2)
My output is
6 5
7 5
8 5
9 5
However, I want it to be
1 0
3 1
5 2
7 3
I'm not quite sure where i'm going wrong and any help would be appreciated.
You need to use the index into x to get the appropriate value of f to use as j. You can do this by iterating over the enumerated x:
x=[1,2,3,4]
f=[0,1,2,3]
for idx, i in enumerate(x):
j = f[idx]
ans = i+j
ans2 = j
print(ans,ans2)
Alternatively you could use zip and iterate both values at once:
for i, j in zip(x, f):
ans = i+j
ans2 = j
print(ans,ans2)
In both cases the output is:
1 0
3 1
5 2
7 3

How to save and work with previous iteration in loop?

You could somehow hold it in a loop after the first iteration and store it in a variable and then continue on. So that in one variable there is a standard loop and in the other a previous loop?
example:
import numpy as np
for j in np.arange(0,5):
print(j)
0
1
2
3
4
5
6
i need example
0
1 0
2 1
3 2
4 3
5 4
6 5
just save the variable you want to print next, and print it before change it with the next one
num = 0
for j in np.arange(0,5):
print(num)
num = j
import numpy as np
for j in np.arange(0,7):
if j == 0:
print(j)
continue
print(j, j-1)
Use zip and itertools.tee:
itr1, itr2 = tee(np.arange(0, 5))
i, j = next(itr1), None
print(i, j)
for i, j in zip(itr1, itr2):
print(i, j)
outputs
0 None
1 0
2 1
3 2
4 3
The question is poorly worded, but here's a good basic iteration. It keeps track of the current variable, as well as saving it.
In [161]: alist = [1,3,6,9,12]
...: blist = []
...: latest = None
...: for item in alist:
...: blist.append(item)
...: print(latest, blist[-1])
...: latest = item
...: print(blist)
None 1
1 3
3 6
6 9
9 12
[1, 3, 6, 9, 12]
In the iteration, the current value is item, the previous is latest. blist[-1] is the last added item.

How to use 2 index variable in a single for loop in python

In C language we can use two index variable in a single for loop like below.
for (i = 0, j = 0; i < i_max && j < j_max; i++, j++)
Can some one tell how to do this in Python ?
With zip we can achieve this.
>>> i_max = 5
>>> j_max = 7
>>> for i, j in zip(range(0, i_max), range(0, j_max)):
... print str(i) + ", " + str(j)
...
0, 0
1, 1
2, 2
3, 3
4, 4
If the first answer does not suffice; to account for lists of different sizes, a possible option would be:
a = list(range(5))
b = list(range(15))
for i,j in zip(a+[None]*(len(b)-len(a)),b+[None]*(len(a)-len(b))):
print(i,j)
Or if one wants to cycle around shorter list:
from itertools import cycle
for i,j in zip(range(5),cycle(range(2)):
print(i,j)
One possible way to do that is to iterate over a comprehensive list of lists.
For example, if you want to obtain something like
for r in range(1, 3):
for c in range(5, 7):
print(r, c)
which produces
# 1 5
# 1 6
# 2 5
# 2 6
is by using
for i, j in [[_i, _j] for _i in range(1, 3) for _j in range(5, 7)]:
print(i, j)
Maybe, sometimes one more line is not so bad.
You can do this in Python by using the syntax for i,j in iterable:. Of course in this case the iterable must return a pair of values. So for your example, you have to:
define the list of values for i and for j
build the iterable returning a pair of values from both lists: zip() is your friend in this case (if the lists have different sizes, it stops at the last element of the shortest one)
use the syntax for i,j in iterable:
Here is an example:
i_max = 7
j_max = 9
i_values = range(i_max)
j_values = range(j_max)
for i,j in zip(i_values,j_values):
print(i,j)
# 0 0
# 1 1
# 2 2
# 3 3
# 4 4
# 5 5
# 6 6

A loop for adding list element without high memory performance?

Everybody,
a =[0, 0, 2, 4, 6]
x=5
This a list (a) and a fix value (x).
I need a loop codes which must add with x every element of list and add this value with previous list elements in every loop ( loop must continue as x value). Other words result should like below:
0
0
2
4
6
0
0
7
9
11
0
0
12
14
16
0
0
15
19
21
0
0
21
24
26
I prepared codes as below but it doesn’t work. Other words produce something as below (incorrect)
i=0
counter=0
while counter < x:
for i in a:
if i >0:
i=i+x
elif i ==0:
i=0
print i
counter=counter+1
0
0
7
9
11
0
0
7
9
11
0
0
7
9
11
0
0
7
9
11
0
0
7
9
11
So, I need to help for this…
Thank you.
I think this does mostly what you want (at least, as I understand the question)...
def make_it_so(a, x):
i = 0
counter=0
while counter < x:
for i in a:
if i == 0:
yield 0
else:
yield i + counter * x
counter = counter + 1
# Demo
for item in make_it_so([0, 0, 2, 4, 6], 5):
print item
Note that I've made it a generator function. You could easily turn it into a regular function that returns a list if you created an output list at the top of the function and swapped yield ... for output_list.append(...) and then return output_list at the end of the function...
The key here is to understand that in the first loop, you are adding 0 to all of the (non-zero) items. In the second loop, you are adding x. In the third loop, you're adding the x + x (since the first loop added x and now you're adding x more). In general, for the Nth loop, you'll be adding (N-1) * x to all of the non-zero items. So, you just need to keep track of N, (or N-1). In fact, your original code was already doing this (with counter), so we just re-purpose that and it's all good.
You need to change the values in a, not just add to the numbers you get out of a (because you'll keep getting the same ones out). Also, you need to print out the original values.
def process(x, memo):
return [n+x if n else n for n in memo]
res = a
memo = a
for _ in range(x - 1):
memo = process(x, memo)
res.extend(memo)

PYTHON: Print X items of a list

I have this code:
U = [1,2,3,4,5,6,7,8,9,10,11,12]
def bla(anzahl):
zaehlwerk = 0
while zaehlwerk < anzahl:
for x in U:
zaehlwerk = zaehlwerk +1
print x
my query:
bla(3)
I hoped that now I would get the first 3 list items, but instead I get the whole list.
1
2
3
4
5
6
7
8
9
10
11
12
I tried to debug because I thought that maybe the counter wouldn't work, but it does. But then where is my error?
use slicing :
>>> U = [1,2,3,4,5,6,7,8,9,10,11,12]
>>> U[:3]
[1, 2, 3]
U[stat-index:end-index], you will get element from start-index to one less end-index, as in above example
>>>U[2:6]
[3, 4, 5, 6]
what you need to do is this using slicing:
def print_list(n):
print "\n".join(map(str,U[:n]))
print_list(3)
output:
1
2
3
for x in U:
is the innermost loop. That is making sure you iterate over everything.
As is you can modify your code to look like
def bla(anzahl):
zaehlwerk = 0
while zaehlwerk < anzahl:
x = U[zaehlwerk]
zaehlwerk = zaehlwerk +1
print x
And that will work for what you want. But more concise would be to to use something like
for index in range(len(anzahl)):
print U[index]

Categories