Reputation: 73
I am quite new to the python coding scene and is currently working on a code on Python using a ultrasonic sensor, I want to add the output value into a list (maintaining the list size)where the list is constantly updating with the latest value from the ultrasonic sensor basically OVERWRITTING the list in a sense,
I have seen examples of Append but they are from fix values,
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a + b
[1, 2, 3, 4, 5, 6]
is there anyway to append with the output from the ultrasonic sensor? Thank you very much
my_list=[100,50,10,20,30,50] #current list
#example of expected output
distance=300
distance=250
distance=230
my_list=[230,250,300,100,50,10]
# the latest 3 reading will be appended to the front of the list
# while still maintaining the size of my_list
Do let let me know if further clarification or information is needed, thank you in advance.
Upvotes: 0
Views: 1026
Reputation: 779
You can append to the front with the insert function
my_list.insert(0, distance)
and delete last element with
del my_list[-1]
Here I am assuming you are getting sensor data within a loop one at a time.
Upvotes: 1
Reputation: 2277
you can do this:
distance = 300
distance = 250
distance = 230
my_list = [230, 250, 300, 100, 50, 10]
my_list.append(20)
print(my_list)
this will append 20 to the list and the result is [230, 250, 300, 100, 50, 10, 20]
and if you like to append it to a certain position of your list, then use insert
distance = 300
distance = 250
distance = 230
my_list = [230, 250, 300, 100, 50, 10]
my_list.insert(0, 20) # 0 is the position and 20 is what to append
print(my_list)
at this code, 0 is the position and 20 is what to append. you can change the value
After reading your question carefully this is the code:
my_list=[100,50,10,20,30,50] #current list
threelist = []
for _ in range(4):
distance=300 # your senser value
threelist.append(distance)
while len(threelist) > 3:
del threelist[0]
my_list = threelist + my_list
while len(my_list) > 6:
del my_list[-1]
print(my_list)
this code appends distance to threelist then +
it to the my_list. and del
the last 3 value.
and you can change distance=300
to your senser value.
I hope this helped you.
Upvotes: 1
Reputation: 969
For every value, you can use my_list.insert(0, new_value)
which will insert new value to 1st position. Your code will look something like:
my_list.insert(0, new_distance) # add new value to beginning (0 index)
my_list = my_list[:-1] # remove last element to keep the size same
You can also combine those, eg: my_list[:-1].insert(0, new_distance)
Upvotes: 1