I can't add input() in python list - python

`i = 0
while i < 5
i=i+1
li = []
li.insert(i,input('>>>'))
print(li)`
When I run this program. It only print last input by me.
Help please.
I want add all input in one by one...

Try this:
li = []
i = 0
while i < 5:
i=i+1
li.insert(i,input('>>>'))
print(li)
And if you want to store numbers as integer, try this:
li = []
i = 0
while i < 5:
i=i+1
li.insert(i,int(input('>>>')))
print(li)

Don't reset your list to an empty list [] on each loop.
Rather than controlling your index yourself, you can use a range.
Also, use append to append an item to your list.
So, your code could become:
li = []
for i in range(5):
li.append(input('>>>'))
print(li)

Use list comprehension for syntactic sugar. Also yeah to reiterate what others have said above, you reset the list on every iteration. Two, input() is a function that returns raw input(usually interpreted as string) so you need to either control its type return or use Regex to ensure you pull only specific answers(really constraining inputs is good practice). Finally when you iterate over a segment it could be easier to do so as a generator function for memory purposes- look into yield and generative functions.
newList = [int(input(‘>>>’)) for x in range(1,5)]
Print(newList)
See a single line could create the list you expected

Related

Need to make a list from a function

I want to change the a variable from 1 to 50 and create an array from the results so that I can feed it into a curve.
The variable is outside the function but the variable changes a value in the function, that is what I need to make a list of.
a=1
def test(foo):
p =a+2
print(p)
test(foo)
I want to get the p values when I change a from 1 to 50:
[3,4,5,6,7,8,9...]
Not sure what you trying to do but if you need a list of numbers with some starting point, you can simply generate them using list comprehension as:
a = 2
x = [i+a for i in range(1, 50)]
print(x)
EDIT: Based on comments from author.
You need to change print to return the generated number. Also, need to add a loop and a list to generate a new number and keep appending the new number to the list.
Note: As said earlier, it is recommended to use Python's supported features like list comprehension as is shown in the original code.
a = 1
def test(i):
p = a + i
return p
res = []
for i in range(2, 50):
res.append(test(i))
print(res)

Python pop and append are not moving all elems in list1 to list 2

Why do pop and append not finish out the entire loop? My first guess was that pop didn't readjust the index of the original list, but that doesn't appear to be true when I print(txt[0]) to confirm it's still at the front. I'm trying to figure out why the below does not work. Thank you.
txt = 'shOrtCAKE'
txt = list(txt)
new_list = []
for x in txt:
value = txt.pop(0)
new_list.append(value)
print(new_list)
print(txt)
print(txt[0])
You shouldn't modify the list while iterating over it. Instead use this code
for x in txt:
value = x
new_list.append(value)
txt = [] # assuming you want txt to be empty for some reason
But then if you end up printing txt[0] you'll end up with error as the list index will be out of range
However you don't really need to be looping. Just do the following:
new_list = txt[:] # [:] ensures that any changes done to txt won't reflect in new_list
You should not remove elements from a list that you are iterating over. In this case, you are not even using the values of the list obtained during iteration.
There are various possibilities if you still want to use pop, which don't involve iterating over txt. For example:
Loop a fixed number of times (len(txt) computed at the start):
for _ in range(len(txt)):
new_list.append(txt.pop(0))
Loop while txt is not empty:
while txt:
new_list.append(txt.pop(0))
Loop until pop fails:
while True:
try:
new_list.append(txt.pop(0))
except IndexError:
break
Of course, you don't have to use pop. You could do this for example:
new_list.extend(txt) # add all the elements of the old list
txt.clear() # and then empty the old list

Python - Removing first two occurrences of element in list

The objective of this function is to remove the first two occurrences of n in a list.
Below is a code I had written but I still got it wrong after many hours. A friend advised me not to edit a list while iterating. However, I'm still stuck.
def remove_first_two(list,n):
if list == []:
return []
else:
count = 0
for ele in list:
if ele == n:
list.remove(ele)
count += 1
if count == 2:
break
return list
list = [1,2,2,3]
print(remove_first_two(list,2)) => [1,2,3] instead of [1,3]
Use list.remove twice with try-except. That will delete first two entries. Complexity O(n)
list_a = [1,2,3,4]
try:
list_a.remove(n)
list_a.remove(n)
# run a loop too, if it's more than 2
except:
pass
You can try find all indexes and del:
a = [1,2,3,2,3,2,4]
indices = [i for i, x in enumerate(a) if x == 2]
print(indices)
[1, 3, 5]
del a[indices[0]], a[indices[1]]
print(a)
[1, 3, 2, 2, 4]
First, don't use 'list' as its a key word in Python. Use something else, like 'alist'.
The code below does what you want and keeps the basic form of what you already have. You can of course also use the built-in .remove() method.
def remove_first_two(alist, n):
if alist == []:
return []
else:
count = 0
while count < 2:
for ele in alist:
if ele == n:
alist.remove(ele)
count += 1
return alist
alist = [1,2,2,3]
print(remove_first_two(alist,2)) # Output -> [1,3]
When your friend says "do not edit a list while iterating," he/she is right, and what he/she means is that you should create another list all together. What you are looking to do is the following:
def remove_first_two(list, n):
if list == []:
return []
else:
new_list = []
count = 0
for ele in list:
if ele == n:
if count >= 2:
new_list.append(ele)
count += 1
else:
new_list.append(ele)
return new_list
However, note that you can use use some built in functions to make your life much easier:
list.remove(x)
Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.
Therefore, you can more simply do:
def remove_first_two(list, n):
if list == []:
return []
for _ in range(2):
if n in list:
list.remove(n)
return list
Python updates the list if you change it while iterating.
In you test case with list = [1,2,2,3] when list[1] is deleted and Python updates list = [1,2,3]. Now Python understands you have iterated till index 1 and continues from index 2 which now contains 3. So Python encounters only one occurance of 2.
So heed your friends advice and do not edit list while iterating :)
Now you can use Python's in-built list.remove(element) to delete first ocuurence of a element. Repeat it 2 times for desired output.
Also O(n) with a single parse.
def remove_first_two(mylist,n):
counter = 0
def myfilter (i):
nonlocal counter,n
if counter > 2:
return True
else:
counter += 1
return (i != n)
return (list(filter(myfilter,mylist)))
This can also be done in python 3.8 using assignment expressions in a list comprehension:
data = [1,2,3,2,3,2,4]
count = 2
num = 2
[x for x in data if x != num or (count:=count-1) < 0]
Results:
[1, 3, 2, 2, 4]
Here is the reason why your program does not work:
When you remove an element, the for loop moves on to the next element, but by "moving on" it is actually skipping the element which now occupies the position of the deleted element. It skips the element right after the one you deleted.
The correct way to iterate over a list while you delete elements is making index progression explicit, by using a while loop instead of a for loop, and not increase the index when you delete an element:
i = 0
while i < len(my_list):
if condition:
my_list.pop(i)
else:
i += 1
However, none of this is necessary in your case! Notice that when you use my_list.remove(ele), you are not providing an index as you would with my_list.pop(i), so Python has to search for the first element that matches ele. Although remove will be slower than pop when used by themselves, here remove allows you not use any loops at all, simply do my_list.remove(n) twice!
Last touch: If your list has less than two elements matching n, one of the two my_list.remove(n) commands would return a ValueError. You can account for this exception, knowing that if it happens, your list is ready and requires no further action.
So the code you need is:
try:
my_list.remove(n)
my_list.remove(n)
except ValueError:
pass

Alternate apporach for using a flag in python

What is the best/alternate pythonic way for the code below,
li=["Header",1,2,3,4,5]
l=0
for i in li:
if l == 0:
.....
l += 1
else:
....
You can replace:
l=0
for i in li:
if l ==0:
frobnosticate(i)
l+= 1
else:
twiddle(i)
With:
#do something with header outside the loop
frobnosticate(li[0])
#loop over everything but the first element
for i in li[1:]:
twiddle(i)
li=["Header",1,2,3,4,5]
do_stuff(li[0]) # first ....
for i in li[1:]:
normal_stuff(i) # second ...
This will deal with header first and then iterate through rest of list.
Accessing such pattern of elements using slicing is good enough. However, if data type in your list is not fixed/known, you may also use dictionary to redirect element to specified function:
def access_string_element(string):
....
def access_integer_element(integer):
....
access_table = dict()
access_table[str] = access_string_element
access_table[int] = access_integer_element
...
Then you could use the dict like this:
for element in li:
access_table[type(element)](element)
This way benefits if you are going to handle list containing data with different data type. It would make your loop looks clearer, and easy to manage.
Have Fun ;)

Loop in a list (Python v3) beginner

I am stuck in making a loop that will eliminate the values(from the alist) that are below average.
Thanks for the help.
a=input("Enter a list of values separated by a coma : ")
alist=eval(a)
print("the list is : ",alist)
average = sum(alist)/len(alist)
print("the average is : ",average)
for i in alist:
if alist[i]<average:
alist.remove[i]
You are almost there. Instead of removing elements, select elements you want to retain instead:
alist = [a for a in alist if a>=average]
Your mistake here is that for i in alist: is iterating over list elements themselves, not indexes, so alist[i] is throwing an error (or returning nonsense).
For the "loop" you can use a filter and a lambda function.
above_average = list(filter(lambda x: x >= average, alist))
For the rest of your code, I suggest you clean it up to something which is safer (use of eval is very bad)
import ast
user_string = raw_input('input a list of numbers separated by a commas: ')
alist = list(ast.literal_eval(user_string)))
So, in all, I would write your code as something like this:
import ast
user_string = raw_input('input a list of numbers separated by a commas: ')
numbers = list(ast.literal_eval(user_string)))
average = sum(numbers)/len(numbers)
print('The numbers: {}'.format(numbers))
print('The average: {}'.format(average))
above_average = list(filter(lambda x: x >= average, numbers))
# now do what you want with the above_average numbers.
Other answers tell you how to do it. I'll tell you why it doesn't work:
You iterate over the list and, at the same time, modify it.
This leads to items being missed during the iteration.
Why?
Internally, the iteration works via an index to the list. So it is the same as doing
idx = 0
while True:
try:
i = alist[idx]
except IndexError:
break
idx += 1
if alist[i] < average:
alist.remove(i)
What happens if you are at the element #3, go to the next one and then remove #3? Right, the indexes of the remaining ones move down and you are pointing to the one which formerly was #5. The old #4 is skipped at this test.
(BTW, I don't know if you noticed, I have replaced your [] behind .remove with ().)
You are mixing two ways of iterating a list: By index, and by element. In your loop, i is not the index, but the element of the list itself, thus alist[i] won't work.
If you use the for x in somelist loop, then x is the element itself, not the index of the element. For iterating over the indices, you can use for i in range(len(somelist)), or you could use for i, x in enumerate(somelist) to loop over tuples of index and element.
Also note that removing elements from a list or other kinds of collections while you are looping them generally is a bad idea. Better create a copy of the list.
for x in list(alist): # creates a copy of alist
if x < average: # remember: x is the element itselt
alist.remove(x) # remove element x from list
But the way you do it (with eval of a comma-separated string of numbers), alist is a tuple, not a list, and thus has no remove method at all. Thus you either have to convert it to a list before (alist = list(eval(a)), or use one of the approaches given in the other answers, creating a new list using list comprehension or filter and retaining the "good" elements.
As a general principle for asking StackOverflow questions like this, you should always include example input and output -- show what happens, and what you expect to happen.
In this case, I believe there are two three problems with your code:
Edit: Third, but possibly most importantly, look at glglgl's answer. If you implement the two fixes I describe below, you'll still have one problem: your code won't necessarily remove all the items you want to remove, because it'll skip over some items.
First, you say alist[i], which grabs the element of alist at index i. But saying for i in alist makes i be successive elements in the list already. Example:
mylist = [1, 2, 4]
for i in mylist:
print(i)
Would give you the output:
1
2
4
If you instead said this (which is like what you wrote)
mylist = [1, 2, 4]
for i in mylist:
print(mylist[i])
It wouldn't work as you'd expect, because you'd get the element at index 1, the element at index 2, and then try to get the element at index 4, but that wouldn't exist. You'll get something like this:
2
4
IndexError: list index out of range
Second, your syntax for removing an element is wrong. You should use alist.remove(i) instead of alist.remove[i]. You want to call a function, so you use parentheses. The square brackets are for indexing and slicing.

Categories

Resources