Hello again.
How can i limit my list indexes?
I want my list to take only 3 indexes for example.

Not sure why you want to do this, but one way is to build a ringbuffer ...

import collections

def ringbuffer_append(item, dq=collections.deque(maxlen=3)):
    '''
    mimics a ringbuffer of length 3
    you can change maxlen to your needs    
    '''
    dq.append(item)
    return list(dq)

# testing
mylist = ringbuffer_append('red')
print(mylist)

mylist = ringbuffer_append('green')
print(mylist)

mylist = ringbuffer_append('blue')
print(mylist)

# first item will pop to make room for new item 3
mylist = ringbuffer_append('orange')
print(mylist)

mylist = ringbuffer_append('yellow')
print(mylist)

''' result ...
['red']
['red', 'green']
['red', 'green', 'blue']
['green', 'blue', 'orange']
['blue', 'orange', 'yellow']
'''

Thank you @vegaseat, i learnt something new.

But is there any way to limit a list inorder not to take a new index? I don't want the list to delete any item to make for any new item.
I want the list to only take the first 3 indexes i append, and if i append the forth number, the list refuse to take and append it. I want the list to ignore from the forth append to the end. Just to take the first 3 append numbers.

This will do, create a custom list append ...

def list_append(item, tlist=[], limit=3):
    '''
    append max limit items to a list
    list cannot exceed given limit size
    '''
    if len(tlist) < limit:
        tlist.append(item)
    return tlist

# testing
mylist = list_append('red')
print(mylist)

mylist = list_append('green')
print(mylist)

mylist = list_append('blue')
print(mylist)

mylist = list_append('orange')
print(mylist)

''' result ...
['red']
['red', 'green']
['red', 'green', 'blue']
['red', 'green', 'blue']
'''

Edited 1 Year Ago by vegaseat

@vegaseat can you explaine this part for me please?
I just don't understand something...

dq.append(item)
return list(dq)

For example we have this colors = "red, blue, pink", now if we use print (list(colors)), we get this:

['r', 'e', 'd', ',', ' ', 'b', 'l', 'u', 'e', ',', ' ', 'p', 'i', 'n', 'k']

So how the items (colors) we append into dq and return dq to a list, don't split into letters?

What do you mean by list("string")?
How can i do that with colors = "red, blue, pink"?

This question has already been answered. Start a new discussion instead.