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']
'''

@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?

Yes! Thank you @vegaseat. Your last code was helpful.

if you use list("string"), it will give you a list of the characters in "string".

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.