I'm trying to enter a 100 number square into a 2D list https://i.stack.imgur.com/eSFiO.png with each list containing 10 numbers 1-10,11-20,21-30 and so on. This is my code so far but when I run it in my editor it just keeps running and eventually crashes without printing anything. Please explain to me what I am doing wrong. Thanks
number_square=[[],[],[],[],[],[],[],[],[],[]]
number_list=[1,2,3,4,5,6,7,8,9,10]
for row in number_square:
for number in number_list:
number_square.append(number)
number_list.remove(number)
number_list.append(number+10)
print(number_square)
That's because you aren't accessing the content of neither row nor number in the for loops. Here is a suggestion:
number_square=[[],[],[],[],[],[],[],[],[],[]]
number_list=[1,2,3,4,5,6,7,8,9,10]
i = 0
for row in number_square:
for i in range(len(number_list)):
row.append(number_list[i])
number_list[i] += 10
print(number_square)
Note that the first loop is equivalent to for each. In this syntax, you can't alter the value of the item in a list. In the second loop, I put a "traditional" for loop with range to alter the values in number_list.
There are many changes required in your code. Good effort from your side on trying the code. I have modified the code and probably you can get the logic from it.
number_square=[[],[],[],[],[],[],[],[],[],[]]
number_list=[10,20,30,40,50,60,70,80,90,100]
for i in range(0,len(number_square)):
for j in range(number_list[i]-9,number_list[i]+1):
number_square[i].append(j)
Problems:
Removing from number_list while iterating over it
Appending to number_square instead of row
If I were you, I'd use a list comprehension with ranges instead:
number_square = [list(range(i, i+10)) for i in range(1, 101, 10)]
Due credit to Onyambu for suggesting something similar in a comment
Related
I am studying for my PCEP and in the practice set there is a syntax for referencing lists I don't understand. Given:
numbers = [2, 3, 5, 8]
print(numbers[numbers[0]])
print(numbers[0])
The first print statement I can't understand, how am I getting 5 as the output? The second statement makes sense, it's how I have done it in the past which is index 0 but what is the first print statement doing? Calling a list within a list like a nested list? And how am I getting to index 2 to get the output of 5?
Thanks in advance for your help/time, it's much appreciated.
I've tried changing the refrenced index and counting through the list twice but often times I am seeing an index out of range response, or a number I wasn't expected. e.g, setting the print statement to
print(numbers[numbers[1]])
Gives me the output of '8' and I don't understand how I am to get there with the index of 1.
It is a similar principle as the parentheses in math. If you have nested parentheses you work from the inside out. In the first example the code solves the inner most number[] list.
So number[0] is 2. Then the code use this converted code to solve the next outer list so you can see it as number[2], instead of number[number[0]].
So number[2] is 5.
When you have nested expressions and they're confusing you, the easiest way to understand what's happening is to break it up into multiple statements.
print(numbers[numbers[0]])
is equivalent to
temp = numbers[0]
print(numbers[temp])
The first statement sets temp = 2, so the second statement prints numbers[2], which is 5.
I'm learning python and I'm trying to understand what the for loop means. My assignment is to understand and comment the full code out. I know that the first two lines of code take an input. Can someone tell me what the next lines of code mean? The for loop is extremely confusing. By the way, let's say the input for j_t is 1, 3, 5 and the input for d_t is 2, 4, 6. Hopefully that helps.
# to take inputs
j_t = list(map(int, input("Process times: ").split(",")))
d_t = list(map(int, input("Job Due Dates: ").split(",")))
dict_spt = {}
dict_edd = {}
for i in range(len(j_t)):
dict_spt[int(j_t[i])] = int(d_t[i])
dict_edd[int(d_t[i])] = int(j_t[i])
The above is a segment of the full code. I ran the full code and it allows me to put in input but I need to understand what the for loop actually does/means in plain english.
Python input give you a string input, j_t and d_t are lists made from your inputs but it is still as string in the lists. for loop is actually iterating on your inputs to create dictionnaries which allow you to get j_t from a d_t value and vice versa and in a same time is casting all inputs to integers to make it easier to use i guess.
Hope it is clear enough
The first 2 lines of code take in an input and creates a list out of them (j_t and d_t).
The next 2 lines initializes a dictionary object (dict_spt and dict_edd).
The for loop iterates from 0 to the length of j_t - 1 = 2 which means that it iterates over all the indices of the items in j_t (1,3,5). The first line in the dictionary puts the key-value pair of int(j_t[0]) = 1 , int(d_t[0]) = 2 into the dict_spt dictionary. And it also adds in the key-value pair of int(d_t[0]) = 2 , int(j_t[0]) = 1 (which is same like the first one but reversed) into the dict_edd dictionary. It does this until the last element (5) is reached.
Hopefully this explanation is clear.
The for loop is your standard construct for iterating through arrays of data. I'll walk you through the whole code.
So in python you have multiple types of, let's call them "array like" structures. In this example you've shown, you have lists and dictionaries. Lists are very similar to standard arrays, where as dictionaries are an "array" of key value pairs.
Now the first two lines take your comma separated inputs and turn them into lists.
Then you create two empty dictionaries - that's indicated by the curly brackets, those are used for defining dictionaries.
Then you have the actual for loop - the best way to read the for line would be:
"For each element i in the range() from zero to the length of thej_t list, do the following"
Important to note that i or whatever you put after the for keyword is a variable that is created on the fly simply for the purpose of iterating through the piece of data you're iterating.
And then in the for loop what you are doing is adding a new record to each dictionary where the key and the value are the integer value of each list element.
Arrays and lists have indexes for every element inside of them so all the standard for loop needs is a numerical range which would represent every index in the structure you're iterating through.
Hope this was clear enough.
I have the following code.
for idx in range(len(networks)):
net_ = networks[idx]
lastId=0
for layerUptID in range(len(net_[1])):
retNet,lastId=cn_.UpdateTwoConvLayers(deepcopy(net_),lastId)
networks.append(retNet)
if(lastId==-1):
break
networks has only one net at the beginning.
After running the line retNet,lastId=cn_.UpdateTwoConvLayers(deepcopy(net_),lastId), I have additional six nets and appended to networks.
So after this lastId ==-1, go back to first for loop with len(networks) is 7.
For the next idx, idx=1 and continue.
Then, len(networks) is 13. Then go back to first for loop.
After this, the first for loop breaks.
I am expecting to continue for idx is 2, but it breaks.
What could be the issue?
If you try using a WHILE loop instead of FOR loop, the break statement would be check if the loop is on the last item in 'networks' collection.
This way the network length would be calculated in each loop iteration
For starters: Iterating, or looping, over the list (or data) you're editing is bad practice. Keep that in mind while coding.
This means if you plan to edit what you're looping on, in your case networks, then you're going to have a bad time looping over it. I would advise to break it up into two code parts:
The first part creates a new list of whatever it is you want WHILE looping.
The second part replaces the list you've used to generate what you wanted.
Another thing which could go wrong is net_[i] may not be set up for some i, and you're trying to access it here:
for layerUptID in range(len(net_[1])):
What if there is nothing in net_[1]?
To avoid these errors, usually verifying your data is a great way to start. If it is not null, then proceed, otherwise, print an error.
This is what I can think of. Hope it helps.
If I understood correctly your problem is that you've added new elements to networks, i.e. have increased length of networks and expect that for-loop will pick up this changes, well it's not, let's look at following snippet
elements = [1]
indices = range(len(elements))
for index in indices:
print('index is', index)
elements.append(2)
print('elements count is', len(elements))
print('indices count is', len(indices))
outputs are
index is 0
elements count is 2
indices count is 1
so as we can see despite the fact that length of elements list has changed, range object which is used in for-loop has not. This happens because len returns int object which are immutable, so when you change list length its length becomes different object and range function has no idea about this changes.
Finally, we can use while loop here like
while networks:
net_ = networks.pop()
lastId = 0
for layerUptID in range(len(net_[1])):
retNet, lastId = cn_.UpdateTwoConvLayers(deepcopy(net_), lastId)
networks.append(retNet)
if lastId == -1:
break
When I run the following code, it prints. However, I expected only one 1 rather than two.
for i in (1,1):
print(i)
Output
1
1
You are iterating over a tuple which contains two elements with value 1 so it prints 1 twice. Your code is equivalent to:
list = [1, 1]
for item in list:
print(item)
If you want to loop over a range of numbers:
for i in range(1, 2):
print(i)
Or if you want to print unique numbers or values in list or tuple convert it into the set it will automatically remove the duplicates
newList = set(list)
for value in newList:
print(value)
Sets and tuples are different. I suspect you are confusing them. On a set:
for i in {1, 1}:
print(i)
1
On a tuple:
for i in (1, 1):
print(i)
1
1
Think of sets as being like sets in math, and tuples as being more like sequences - you can have redundancies in a sequence, but not in a set.
After reading #KeshavGarg's answer, I suspect you thought that (a,b) in Python would mean stuff in a through b. As you're probably aware by now, this is not the case - you need range to get that. Interestingly (and I admit tangentially), the syntax we're discussing here varies by language. In MATLAB, the range syntax looks a lot more like what I assume you thought the Python range syntax was:
>> for i=1:4
disp(i)
end
There has been some discussion of implementing range literals (a la Matlab) in Python. This introduces a variety of interesting new problems, which you can read about in the documentation linked in the previous sentence.
For loops are always inclusive in Python: they always run over all elements of the iterator (other than exceptions such as break, etc.). What probably has you confused is the range syntax. range(1,1) will create a range object with one element. It is the range function, not the for-loop, that is exclusive, in the sense of not including the stop argument in the range object.
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
import os
os.chdir('G:\\f5_automation')
r = open('G:\\f5_automation\\uat.list.cmd.txt')
#print(r.read().replace('\n', ''))
t = r.read().split('\n')
for i in range(len(t)):
if ('inherited' or 'device-group' or 'partition' or 'template' or 'traffic-group') in t[i]:
t.pop(i)
print(i,t[i])
In the above code, I get an index error at line 9: 'if ('inherited' or 'device-group'...etc.
I really don't understand why. How can my index be out of range if it's the perfect length by using len(t) as my range?
The goal is to pop any indexes from my list that contain any of those substrings. Thank you for any assistance!
This happens because you are editing the list while looping through it,
you first get the length which is 10 for example, then you loop through the thing 10 times. but as soon as you've deleted one thing the list will only be 9 long.
A way around this is to create a new list of things you want to keep and use that one instead.
I've slightly edited your code and done something similar.
t = ['inherited', 'cookies', 'device-group']
interesing_things = []
for i in t:
if i not in ['inherited', 'device-group', 'partition', 'template', 'traffic-group']:
interesing_things.append(i)
print(i)
Let's say len(t) == 5.
We'll process i taking values [0,1,2,3,4]
After we process i = 0, we pop one value from t. len(t) == 4 now. This would mean error if we get to i = 4. However, we're still going to try to go up to 4 because our range is already inited to be up to 4.
Next (i = 1) step ensures an error on i = 3.
Next (i = 2) step ensures an error on i = 2, but that is already processed.
Next (i = 3) step yields an error.
Instead, you should do something like this:
while t:
element = t.pop()
print(element)
On a side note, you should replace that in check with sets:
qualities_we_need = {'inherited', 'device-group', 'partition'} # put all your qualities here
And then in loop:
if qualities_we_need & set(element):
print(element)
If you need indexes you could either use one more variable to keep track of index of value we're currently processing, or use enumerate()
As many people said in the comments, there are several problems with your code.
The or operator sees the values on its left and right as booleans and returns the first one that is True (from left to right). So your parenthesis evaluates to 'inherited' since any non-empty string is True. As a result, even if your for loop was working, you would be popping elements that are equal to 'inherited' only.
The for loop is not working though. That happens because the size of the list you are iterating over is changing as you loop through and you will get an index-out-of-range error if an element of the list is actually equal to 'inherited' and gets popped.
So, take a look at this:
import os
os.chdir('G:\\f5_automation')
r = open('G:\\f5_automation\\uat.list.cmd.txt')
print(r.read().replace('\n', ''))
t = r.read().split('\n')
t_dupl = t[:]
for i, items in enumerate(t_dupl):
if items in ['inherited', 'device-group', 'partition', 'template', 'traffic-group']:
print(i, items)
t.remove(items)
By duplicating the original list, we can use its items as a "pool" of items to pick from and modify the list we are actually interested in.
Finally, know that the pop() method returns the item it removes from the list and this is something you do not need in your example. remove() works just fine for you.
As a side note, you can probably replace your first 5 lines of code with this:
with open('G:\\f5_automation\\uat.list.cmd.txt', 'r') as r:
t = r.readlines()
the advantage of using the with statement is that it automatically handles the closing of the file by itself when the reading is done. Finally, instead of reading the whole file and splitting it on linebreaks, you can just use the built-in readlines() method which does exactly that.