So I have a matrix like:
1 2 3 4
0 3 4 1
7 3 4 5
And I want to select a row,then use this row to do stuff on it such as sorting it with some algorithms;I made this so far:
def row_management(matrix):
theline = input('wich line?') #enter row number
thelist = [matrix[theline]] #go take the right row of the matrix
menu_thelist(thelist) #supossed to use the row and take it to the list management menu
However, when I run this, it always return an error "[matrix[theline]] TypeError: list indices must be integers, not str" and I don't get it.
The input call returns a str type, so it can not be used directly as index to the list inmatrix[theline], which is also what the error message says. Instead do:
matrix[int(theline)]
Needed to convert to int
theline = int(input('wich line?'))
And also
thelist = matrix[theline]
the have [1,2,3] and not [[1,2,3]](wich cause further problem)
Related
This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 1 year ago.
data = [1, 2, 3, 4, 5]
for x in data:
print(x)
if data.count(x) < 2:
data.remove(x)
Hello Guys,
so I am currently working through py.checkio.org and am at a point where I have to remove all the numbers that are unique in a list.
When I run my code without the if statement I get an output counting from 1 to 5. But once I run the for loop with the if statement the for loop only runs through the data for every second number and my output is 1 3 5. Can anyone please tell me what is happening here?
While the from #Stef and #0x5453 are both relevant to your problem. The comment from #ConnorTJ is patently wrong. The remove function does not remove the item at the index but the first occurrence of the item.
To answer your question, about what's going on here, let[s examine your code:
The first pass through the value of x is 1
You print the value of x
You then test to see if the number of occurrences of x is less than 2
Since the answer is yes, you proceed to remove the item from the list.
The second pass through the list the For loop picks up the next value in the list (at index 1) which is now the value 3
You print the value 3
You check to see if the count of 3 is less than 2
Since the count is less you remove that item from the list.
This process than continues
Simple solution, use filter()
Construct an iterator from those elements of iterable for which function returns true
it returns a list of the list items that the function returned true for.
example:
x = [1,1,2,2,3,4]
x = filter(lambda f: (x.count(f)<2), x)
x = list(x)
print(x)
or in short: print(list(filter(lambda f: (x.count(f)>=2),x)))
output is [1,1,2,2]
I am trying to write a function which will return True or False if the given number is not greater than 2.
So simple, but the if condition is returning different outputs for same value '2'. The code I used is:
The code I used is:
ele_list = [1,2,3,2]
for i in ele_list:
if not i>2:
print(i,False)
ele_list.remove(i)
print(ele_list)
The ouput I am receiving is:
1 False
[2, 3, 2]
2 False
[3, 2]
I am confused to see that the first 2 in the list is passing through the if condition but the second 2 in the list is not passing through the condition. Please help me figure out this..
Removing elements from the list you're looping over is generally a bad idea.
What's happening here is that when you're removing an element, you're changing the length of the array, and therefor changing what elements are located at what indexes as well as changing the "goal" of the forloop.
Lets have a look at the following example:
ele_list = [4,3,2,1]
for elem in ele_list:
print(elem)
ele_list.remove(elem)
In the first iteration of the loop elem is the value 4 which is located at index 0. Then you're removing from the array the first value equal to elem. In other words the value 4 at index 0 is now removed. This shifts which element is stored at what index. Before the removal ele_list[0] would be equal to 4, however after the removal ele_list[0] will equal 3, since 3 is the value that prior to the removal was stored at index 1.
Now when the loop continues to the second iteration the index that the loop "looks at" is incremented by 1. So the variable elem will now be the value of ele_list[1] which in the updated list (after the removal of the value 4 in the previous iteration) is equal to 2. Then you're (same as before) removing the value at index 1 from the list, so now the length of the list just 2 elements.
When the loops is about to start the third iteration it checks to see if the new index (in this case 2) is smaller than the length of the list. Which its not, since 2 is not smaller than 2. So the loop ends.
The simplest solutions is to create a new copy of the array and loop over the copy instead. This can easily be done using the slice syntax: ele_list[:]
ele_list = [1,2,3,2]
for elem in ele_list[:]:
if not elem > 2:
print(elem, False)
ele_list.remove(elem)
print(ele_list)
the problem is that you're modifying your list as you're iterating over it, as mentioned in #Olian04's answer.
it sounds like what you really want to do, however, is only keep values that are > 2. this is really easy using a list comprehension:
filtereds_vals = [v for v in ele_list if v > 2]
if you merely want a function that gives you True for numbers greater than 2 and False for others, you can do something like this:
def gt_2(lst):
return [v > 2 for v in lst]
or, finally, if you want to find out if any of the values is > 2 just do:
def any_gt_2(lst):
return any(v > 2 for v in lst)
I think the problem here is how the remove function interacts with the for function.
See the documentation, read the "note" part:
https://docs.python.org/3.7/reference/compound_stmts.html?highlight=while#grammar-token-for-stmt
This can lead to nasty bugs that can be avoided by making a temporary copy using a slice of the whole sequence
A possible solution, as suggested into the documentation:
ele_list = [1,2,3,2]
for i in ele_list[:]:
if not i>2:
print(i,False)
ele_list.remove(i)
print(ele_list)
"""
1 False
[2, 3, 2]
2 False
[3, 2]
2 False
[3]
"""
For example, if your niece is turning 4 years old, and the cake will have 4 candles of height 4, 4, 1, 3, she will be able to blow out 2 candles successfully, since the tallest candles are of height 4 and there are such
2 candles.
Sample Input
4
3 2 1 3
Sample Output
2
Here's my code
def birthdayCakeCandles(ar):
candle = []
for i in ar:
if ar[i] == max(ar):
candle.append(ar[i])
print(len(candle))
In Pycharm, there's something trouble in """if[i] == max(ar)"""
It says index error but I don't know why it causes index error..
You are confusing two concepts on how to iterate through a list.
Also we don't need a list, we just need a variable candles which keeps count of number of valid candles
The first way is to pick each element in the list and use it, we do it by doing for elem in list, where elem=4,4,1..
def birthdayCakeCandles(ar):
candles = 0
#Maximum value in array
max_arr = max(ar)
#a in an element in ar
for a in ar:
if a == max_arr:
candles+=1
print(candles)
The second method is to get the indexes of the list and use those indexes to iterate, i.e. for i in range(len(ar)) where i=0,1,2... etc.
def birthdayCakeCandles(ar):
candles = 0
max_arr = max(ar)
#i is the index in ar
for i in range(len(ar)):
if ar[i] == max_arr:
candles+=1
print(candles)
In both cases, the output is 2
All -
For a Selenium webscraper using Python 3.x - I am trying to get a printout that depends upon the length of each 1d index in a jagged list, in this case only 2d. The list is named masterViewsList, and the lists it contains are versions of a list named viewsList. Below see how my list masterViewsList of viewsList's is constructed:
from selenium import webdriver
import os
masterLinkArray = []
masterViewsList = []
# a bunch of code here that I cut out for simplicity's sake
for y in range(0, len(masterLinkArray)):
browser = webdriver.Chrome(chromePath)
viewsList = []
browser.get(masterLinkArray[y])
productViews = browser.find_elements_by_xpath("// *[ # id = 'lightSlider'] / li / img")
counter = - 1
for a in productViews:
counter = counter + 1
viewsList.append(a.get_attribute('src'))
print(viewsList[counter])
print(len(viewsList))
masterViewsList.append(viewsList)
if y == 10:
print(masterViewsList[y])
print(len(masterViewsList[y]))
del viewsList[:]
print(len(masterLinkArray))
print(len(masterViewsList))
print(len(masterViewsList[0]))
print(len(masterViewsList[1]))
print(len(masterViewsList[10]))
The printout is this:
["https://us.testcompany.com/images/is/image/lv/1/PP_VP_L/544_PM2_Front%20view.jpg?wid=140&hei=140","https://us.testcompany.com/images/is/image/lv/1/PP_VP_L/544_PM1_Side%20view.jpg?wid=140&hei=140","https://us.testcompany.com/images/is/image/lv/1/PP_VP_L/544_PM1_Interior%20view.jpg?wid=140&hei=140","https://us.testcompany.com/images/is/image/lv/1/PP_VP_L/544_PM1_Other%20view.jpg?wid=140&hei=140","https://us.testcompany.com/images/is/image/lv/1/PP_VP_L/544_PM1_Other%20view2.jpg?wid=140&hei=140"]
5
79
79
0
0
0
As you can see, neither the masterLinkArray, nor the masterViewsList are empty - they're 79 long. Also, print(masterViewsList[y]) prints out an actual non-empty list, one with a recognized length of 5. Oddly, once I leave the for y loop, len(masterViewsList[*any integer*]) prints out to "0". These similar questions:
Find the dimensions of a multidimensional Python array,
Find length of 2D array Python,
both indicate that len(array[*integer*]) is the proper way to get the length of a list within a list, but in my case this appears not to be working consistently.
The masterViewlist is empty a the point where you call the len method on it. That's why all the results of the len method will be zero.
In the first short version of your code this is not clear because the following line of code is missing in that version:
del viewsList[:]
After appending the viewList to masterViewList, this line of code causes the masterViewlist being empty again. This is because the del command deletes all references to this viewList including the one in the masterViewlist. You can remove this del of the viewList because you starts with a new viewList every time you are back in the beginning of the outer for loop.
When I execute this code:
import random
list1 = ['afgdddd', 'bcbvnbn', 'casretb', 'dbcbv ', 'egfhsgs']
list2 = ['a5y5546', 'brtewtwret', 'chrtyey', 'dqawtet', 'egreg']
choice1 = random.randint(0, len(list1))
print(list1[choice1])
print(list2[choice1])
Sometimes a get this error:
python IndexError: list index out of range
What is causing this?
Valid list indices for a list of length 5 are 0,1,2,3,4. You are choosing a random number from 0,1,2,3,4,5. When the random number is 5 your index is out of range just as the error message says.
To prevent this from occurring you need a random number between 0 and 4. Simply change to:
choice1 = random.randint(0, len(list1) - 1)
Subtracting 1 from the length of a list is a very common pattern to get the last element in an array.
To debug something like this yourself, you should print(choice1) before trying to print(list1[choice1]) to see why the index may be out of range.