Not access to while loop in - python

I am new in Python. In this try I think can not access elements in while loop!? How to reach all element in list, first, second, third,.... Please some help.
Here my code:
my_list=[5,8,9,10,22]
l=len(my_list)
# only for test output
print("My list has "+str(l)+" elements.")
while my_list[l-1]<1:
print (my_list[l-1])
if my_list[l-1]<1:
print(my_list[l-1])
l+=1 `

in your code, you are saying
while my_list[l-1] < 1:
but my_list[l-1] is equal to 10.
10 > 1 so it will never enter your loop.
If you want to print all the elements, you should use a for loop.
If you really want to use a while loop, what you can do is:
my_list = [5,8,9,10,22]
my_list_len = len(my_list)
i = 0
while i < my_list_len:
print(mylist[i])
i+=1
this is an example, and there is many other ways to do that.

Related

Python trying to remove all occurences of an element in an array with a for loop

I'm trying to remove all elements whose text property is equal to "PayLivery" from an array called "prices".
I'm new to python and don't understand why this code doesn't work:
for i in range(len(prices)):
if prices[i].text == "PayLivery":
prices.pop(i)
i-=1
The array(prices) has a length of 37 at the beginning. It throws a "Index Error list index out of range" error at an i value of 25 and a (prices)length of 25.
I hope someone can help me. Thanks in advance.
The idiomatic way to achieve what you want is to use a filtering comprehension:
prices = [p for p in prices if p.text != "PayLivery"]
The reason your code isn't working is because the -= operator during any one loop has no effect on the value of i on the subsequent loop since the value of i is set by the for loop at the start of each loop. Here's a quick demo:
>>> for i in range(5):
... print(i)
... i += 853718234
...
0
1
2
3
4

Why does my variable determining an item in a list become out of range?

So, I'm working on a function that will take a data list, and make a new list with items that repeat over a given number removed. So far, I have this while loop in the function
def solution(data, n):
timesRepeated = n
lengthData = data.__len__()
j = 0
while (j <= lengthData):
num = data[j]
if (check(data, num, n)):
print("Thisimes")
data = (list(filter((num).__ne__, data)))
j = 0
lengthData = data.__len__()
if (j == lengthData):
break
j += 1
The check() function just checks if num appears in the list more than n times and returns True if so. It's working as intended, I'm just missing something in the while loop
So, this is for the Google foobar test, so I don't want a solution to the function, but I just want to know why my j variable goes out of range of data. I keep getting this error: "IndexError: list index out of range" with this function run: solution([1, 2, 3], 0). If anyone could help an aspiring pythonista, it would be appreciated.
Edit: Thanks for the help, looking back on it, I realized my errors. Didn't know that I could just use <, thanks. Also, I just googled the 'data.len()' because I was unfamiliar with list attributes, so I'll replace that. The second if, I'll remove. The intended output would be nothing, since all of the items occur more than 0. I also realized that the 'num = data[j]' wouldn't be accurate since the length changes every iteration. Thanks for the feedback, I'll make those changes and answer this if it works
j <= lengthData will let j reach a value beyond the last index in data which is lengthData-1 because Python list indexes are zero based.
Use while j < lengthData: instead
Ok, so I think I figured out why the num variable kept going out of range. Since I would be removing items, the order of those items would change. Therefore, j would become higher the more iterations the while loop would run, so with the data being [1,2,3] and the n being 0, l would always be higher than 0 which would be the end result of the while loop. Thanks for all the help and suggestions. My work is not done yet, but at least this problem is. Have a good day everyone
Edit: Nevermind, Barmar and Alain T had it right, it was due to the <= not being <. Thanks again

How to grab even numbers into a list in python 3 using for loop

I'm just starting to learn python and I know what I'm asking is so basic but I'll get to it anyway ,
# adding an If statements grabbing the even numbers
evenNumber = [num for num in range(0,11) if num%2==0]
evenNumber
and now I'm trying to do it the organized way using a for loop but I'm missing something :
#adding an If statements grabbing the even numbers using for loop
evenNumber = []
for num in range(0,11):
evenNumber.append(num if num%2==0)
evenNumber
Appreciate the help and please don't mind my easy question :)
Just to point you to the error in your code, I have only rectified the part in your code which had the issue. Try this:
evenNumber = []
for num in range(0,11):
if num % 2 == 0:
evenNumber.append(num)
print(evenNumber)
However, the best way is to use list comprehension.
And you can use the third (optional) parameter of range(), i.e., step if you start your range with an even number and using a step of 2 ensures that you always get an even number.
evenNumber = [num for num in range(0,11,2)]
Or
Simply,
print(list(range(0,11,2)))
The range function has an optional 'step' Parameter, it defaults to 1 but you can change it to any number you want. e.g:
evenNumber = []
for num in range(0,11,2):
evenNumber.append(num)
print(evenNumber)

Python truncating numbers in integer array

I am teaching myself Python and am running into a strange problem. What I am trying to do is pass a list to a function, and have the function return a list where elements are the sum of the numbers around it, but what I thought would work produced some strange results, so I made a debug version of the code that still exhibts the behavior, which is as follows:
When I make an integer array, and pass it to an function which then uses a for loop print the individual values of the list, the numbers following the first one in each int are truncated.
For example, the following input and output:
Please enter a number: 101
Please enter a number: 202
Please enter a number: 303
Please enter a number: .
1
2
3
This happens no matter the input, if its 10, 101, or 13453 - the same behavior happens.
I know I am probably missing something simple, but for the sake of me, no amount of googling yields me a solution to this issue. Attached below is the code I am using to execute this. It is interesting to note: when printing the entire list outside of the for loop at any point, it returns the full and proper list (ie ['101', '202', '303'])
Thanks!
temp = list()
def sum(list):
print list
for i in range(1, len(list)+1):
print i
return temp
L = list()
while True:
input = raw_input("Please enter a number: ");
if input.strip() == ".":
break
L.append(input);
print L
L2 = sum(L)
print L2
The loop
for i in range(1, len(my_list)+1):
print i
iterates over the numbers from 1 to len(my_list), not over the items of the list. To do the latter, use
for x in my_list:
print x
(I've renamed list to my_list to save you another headache.)
You are printing the counter, not the list item. This is what you want:
for i in list:
print i
list is itself iterable and you don't need a counter to loop it.

Creating an empty list to have data assigned afterwards

Lets say that I want to create a list of names
listOfNames = []
Then I have a while loop such as
count = 0
while listOfNames[count] < 10:
nameList[count] = raw_input("Enter a name: ")
count += 1
Python says that the list index is out of range, but the list index should be at 0, correct?
How do add to the list each time the while loop is ran? I'm assuming something is wrong with my list assignment.
An empty list doesn't have any index yet, it's an empty list! If you want to fill it, you have to do something like this :
while count < 10:
nameList.append(raw_input("Enter a name: "))
count += 1
This way, your condition will be evaluated and with the append method, you will be able to add new items in your list.
There are a few advanced tricks to do this easily, but considering your level, I think it's better that you understand this code before moving on.
Most idiomatic is to use a list comprehension:
namelist = [raw_input("Enter a name: ") for i in range(10)]
(or use _ for i, although I personally wouldn't)
This has the advantage of creating the list on the fly, while having to use neither the append() method nor explicit indexing.
count = 0
while listOfNames[count] < 10:
nameList.append(raw_input("Enter a name: "))
count += 1
Use append for quick n easy...
Alternatively:
nameList[len(nameList):] = [raw_input("Enter a name: ")]
Edit: Did you mean listOfNames to be appended as opposed to nameList?
Your list assignment is right, your problem is with your use of indexes which do not yet exist.
count = 0
while listOfNames[count] < 10:
nameList[count] = raw_input("Enter a name: ")
count += 1
I'm fairly sure this code doesn't do what you intend. What this code is doing is checking the first through tenth elements of listOfNames for a number which is less than 10, but since its an empty list there is no element with index 0, or any other index for that matter hence your list index out of range exceptions.
The following will work as you intend:
count = 0
while len(listOfNames) < 10: # Keep going until the list has 10 elements
nameList.append(raw_input("Enter a name: "))
count += 1
However I'd suggest using the following which does exactly the same thing but should be more efficient as well as being more aesthetically pleasing:
for _ in range(10):
listOfNames.append(raw_input("Enter a name:"))
Note the use of append instead of an index reference. This will add the new element on to the end of the list whereas using the index as you were trying to do will fail since to assign to and index there has to be an element present in the first place.

Categories

Resources