'how do i create a list so that when i append a variable the first elelmnt gets removed from list after a certin threshold
lets say i want to create a list. the list need to have a MAX length of 5. the list would operate as such :
list = []
list.append(1)
list = [1]
list.append(2)
list = [1,2]
..
list.append(5)
list = [1,2,3,4,5]
BUT, when I append another number the first element is removed.
list.append(6)
list = [2,3,4,5,6]
this is super basic and I cant figure this one out ! please advise
NOTE: I don't want to use classes , can this be done with basic functions such as slices?
Solution 1:[1]
If you need it to be a list, you can use a slightly different approach to add the items (in-place):
L = []
L[:] = L[-4:] + [1] # [1]
L[:] = L[-4:] + [2] # [1, 2]
L[:] = L[-4:] + [3] # [1, 2, 3]
L[:] = L[-4:] + [4] # [1, 2, 3, 4]
L[:] = L[-4:] + [5] # [1, 2, 3, 4, 5]
L[:] = L[-4:] + [6] # [2, 3, 4, 5, 6]
Which you could place in a function to make it easier to use:
def appendMax(L,maxLen,value): # maxLen > 1
L[:] = L[1-maxLen:] + [value]
L = []
appendMax(L,5,1) # [1]
appendMax(L,5,2) # [1, 2]
appendMax(L,5,3) # [1, 2, 3]
appendMax(L,5,4) # [1, 2, 3, 4]
appendMax(L,5,5) # [1, 2, 3, 4, 5]
appendMax(L,5,6) # [2, 3, 4, 5, 6]
Solution 2:[2]
Use deque() from collections. It will hold certain amount of variables, after that it will delete the first item while appending.
If you don't want to use libraries or classes, you can simply create a list with N none values inside it, then loop inside the list to replace the values inside it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Olca Orakc? |
