How can I use the pop function in a loop to pop from a certain index to a certain index. I need to move the front end of a list to the end and then delete a specific index. Here is my code so far. The idea is to cycle through a list [1,2,3,4,5,6,7....] up until the inputted number. Then it is supposed to delete the inputted number that is the count. The issue arises when needing to move multiple items to the back of the list in the count using the pop function. This code runs for example using the input 7 as the list and 2 as the count,but not 7 as the list and 3 as the count because it can't move more than one index to the back of the list.
def counter(L,m)
for i in range(m):
if len(L) >= m:
del L[m-1]
L.append(L.pop(0))
print("removed this number")
return L
else:
if len(L) < m:
del L[m]
I'm confused. Your last line should cause an index error.
Are you trying to shorten a list to a specific index?
It sounds like you should use slices, though I don't understand exactly what you are trying to do.
truncated = L[m:]
L = L[:m]
for i in truncated:
print("removed this number") #probably want to use interpolation here as well
to move the front to the back use [::-1]
Related
I am new to python and working on basic functions and conditionals.
Here's an example of 1 function in my code:
def oddEven(oe):
if oe % 2 == 0:
print("number is even")
else:
print("number is odd")
There are 3 total functions in my code (omitted because unnecessary). The first two pass the value of the integer named first, and the last function takes two integer parameters and pass both first and second and checks the result.
Here is how I'm recalling these and checking my code
first = 30
second = 60
oddEven(first)
minutes(first)
relation(first, second)
Instructions say:
Run the program five times using the provided first values and your chosen second values, and check your results. You can alternatively run the program once and use a for loop to execute your code five times.
If the values were for example 23, 33, 14, 31 I could just do:
oddEven(23)
oddEven(33)
oddEven(14)
oddEven(31)
Right? And then do the same for the second function and the third. How could I make a for loop for this?
This is simple way to do this :
list_values = [22,33,14,31]
for value in list_Values:
oddEven(value)
You’re right, you use a for loop in order to do that. The previous answers may have been able to iterate through the list for both the evenOdd and minutes functions, but they didn’t handle the case where you compare two consecutive values for your relation function.
Create a list of 5 numbers and iterate through it. Handling the case where you’re comparing two consecutive numbers against each other can be done with a simple if statement that stops executing once you’ve reached the second to the last element in the list.
If you’re not familiar with lists yet, think of them as ‘containers’ for your data; where you can systematically store and access each piece one at a time.
What’s happening in the code is the for loop iterates through the list one element at a time. The function range(n) takes in a number n, for an argument, and then creates a ‘range’ of numbers from 0 to n - 1.(Ex. range(2) will iterate through the for loop 2 times giving i a value of 0 on the first loop and 1 on the second.
An element from a list can be accessed with this notation: list[i], where i is a number that starts from 0 (therefore accessing the first element of the list) and ranges all the way up to the (length of the list - 1). So to access the third element in a list would be done like so: list[2].
The code below is pretty modular so you can add any amount of numbers to the numbers[] list and it should work, given that there is more then 1 number in the list. It’s a good practice to get in the habit of making your code as modular as possible, instead of hard coding in constants. This is done by passing the (length of the list) to the range(), which allows the for loop to iterate over any size list.
If you add only one number to the list ( ex. numbers = [42]), the only thing that would happen is that the code inside the if statement will not execute, as it requires there to be more than 1 number in the list. The oddEven and minute function should still work though. Go ahead and give that a try! Try adding more than 5 numbers to the list too.
numbers = [23, 33, 14, 21, 42]
for i in range(len(numbers)):
first = numbers[i]
oddEven(first)
minutes(first)
if i < (len(numbers) - 1):
second = numbers[i + 1]
relation(first, second)
I'm very new to the world of programming, I've been trying to solve a specific python academic exercise but I ran into an obstacle.
The problem is that I need to generate a lucky numbers sequence, as in the user inputs a sequence [1,...,n] and these steps happen:
Every second element is removed
Every third element is removed
Every fourth element is removed
.
.
.
When it becomes impossible to remove more numbers, the numbers left in the list are "lucky".
This is my code:
def lucky(l):
index = 2
new_list = []
while(index<len(l)):
for i in range(len(l)):
if(i%index==0):
new_list.append(l[i])
index=index+1
return new_list
The while loop is to have the final condition when " it is impossible to remove more numbers". However with every iteration, the list gets shorter more and more, but I don't know how to do it.
My code works for the first condition when index=2(remove every 2nd element), then in the following loops it doesn't work because:
It is still limited by length of the original list.
new_list.append(l[i]) will just add more elements to the new_list, rather than updating it in its place.
I don't know how to update the list without creating multiple amounts of lists and with each iteration adding the new elements to a new list.
Any help is appreciated.
You could use del with appropriate list slicing (see the manual for more details) to update the list in-place:
def lucky(l):
interval = 2
while interval <= len(l):
del l[interval-1::interval]
interval += 1
I am not sure if I understand your question correctly, but you can remove items from your original list via del l[index], where index is the index of the element to be removed.
For more details on lists look here:
https://docs.python.org/3/tutorial/datastructures.html
import math
def lucky(l, index):
for i in range(math.floor(len(l)/index)):
del l[(i+1)*(index-1)]
Not sure if the code will work, as I cannot test it right now. But I think it should work somehow like that.
EDIT:
Tested it and the code works. If you want to run all three steps, just do:
l = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
lucky(l,2)
lucky(l,3)
lucky(l,4)
print(l)
>>>[1,3,7,13,15]
Here's my code
def abc(l,z):
L=[]
länge= len(L)
for x in range(0, länge+1):
L[x]+z
print(L)
abc(["1","2","3"],"-")
I want the program to output "1-2-3"
l in abc(l,z) should be a List out of Strings which combines "l" and "z" to a single String.
I'm getting an Index Error: list index out of range.
There are a couple of issues here.
First, range(0, länge+1) will stop at länge but your list only has indexes from 0 tolänge - 1, so that's one source for an IndexError.
Second, L[x]+z will give you another IndexError because L is empty but you try to access L[0] (and in the next iteration, where you don't get because of the error, L[1], L[2], and so on).
Third, even without an IndexError the statement L[x]+z will do nothing. You compute the value of L[x]+z but then you don't assign any variable to it, so it is immediately lost.
Fourth, in order to print your final result, put the call to print after the for loop, not inside. Consider using return instead of print if you actually want to do something with the result the function produces (make sure to educate yourself on the difference between print and return).
Fifth, you want to build a string, so the usage of the list L does not make much sense. Start with an empty string and add the current item from l and z to it in the loop body (coupled with a re-assignment in order to not lose the freshly computed value).
Lastly, there's no point in using range here. You can iterate over values in a list direclty by simply writing for x in l:.
That should give you enough to work with and fix your code for now.
(If you don't care why your function does not work and this is not an exercise, simply use str.join as suggested in the comments.)
Trying to create insertion sort but receive an error...
Don't really know why it is happening. It always tends to miss 37 aswell
numbers = [45,56,37,79,46,18,90,81,50]
def insertionSort(items):
Tsorted = []
Tsorted.append(items[0])
items.remove(items[0])
for i in range(0,len(items)):
print (Tsorted)
if items[i] > Tsorted[len(Tsorted)-1]:
Tsorted.append(items[i])
else:
Tsorted[len(Tsorted)-2] = items[i]
items.remove(items[i])
insertionSort(numbers)
Error:
if items[i] > Tsorted[len(Tsorted)-1]:
IndexError: list index out of range
First thing: you are removing items from the Array that you are iterating inside the loop here: items.remove(items[i]). This is generally not a good idea.
Second: This algorithm doesn't implement insertion sort, even if you fix the deletion issue. You should review the algorithm, e.g. here Insertion sort in Wikipedia. Thre is another loop required to find the right insertion place.
Third: in the else case, you are overwriting instead of inserting values.
You are removing elements from items over the course of the loop; thus, i may become a value that was a valid index in the original items, but is no longer in the shortened one.
If you need to remove elements from items, it looks like you should wait until the loop is finished.
That's because you're calling tems.remove(). Your code fails when i=4 and items=[37, 46, 90, 50].
So they already has no an element with index 4 but with 3 since indexing starts with 0.
range(0,len(items) will only be calculated the first time your code hits your for-loop, at which state len(list) = 8. Which means that you wlil iterate
for i in [0,1,2,3,4,5,6,7]
#Do stuff...
But at the same time you remove items from your list in each loop. So when hitting i = 4, you have iterated your loop 4 times and the length of you item-list is only 4, which means that items[4]
no longer exists.
I have the following python code:
raw_list = reminders_context['data']['reminder_list']
This statement works fine and gets the required info that I want.
The following code gives me the error list index out of range but the inner workings of the for loop for eg.[I obviously substitute the 'i' value for a number, then get the first 10 characters of the list item with [:10]], work fine when I set a trace in pdb mode.
raw_list[i]['created'][:10] == raw_list[i + 1]['created'][:10]
Code that gives an error:
for i in range(len(raw_list)):
if raw_list[i]['created'][:10] == raw_list[i + 1]['created'][:10]:
del raw_list[i + 1]
else:
pass
How can I change it so that I do not get the error?
I have seen something about how my list gets reduced in the for loop when iterating but I simply do not know how to implement it in my code.
The article I'm referring to is here:
python : list index out of range error
How about changing:
for i in range(len(raw_list)):
into:
for i in range(len(raw_list)-1):
range(n) goes from 0 to n-1. In this case, n-1 is the last valid index in your list. When your loop is on the iteration i = len(raw_list)-1 (the last iteration), your operation to access the i+1th element tries to access len(raw_list) which is not a valid index in the array. So the last valid iteration your loop can do is i=len(rawlist)-2
Basically, you need to make your for loop do one less iteration.