Is it possible to limit the size of list in python.
I want to make list of 5 elements. How can I achieve this thing in python. And one more thing can we declare list to store elements of same type as in c, C++ we can declare an
array which can have 5 elements of type int.
C, C++:
int intarr[5]
How can I achieve this kind of behavior?

Thankx

Hi!

Well, limiting the size is a bit difficult ... I have no idea how this could be done.

For your second question, have a look at the array module.

Regards, mawe

There woud be some way right for limiting the list, right?
Anyways thanks for suggesting array module. But,problem with array module is that I can represent only an array of basic types such as character, int.
But what if I have to declare an array of some user - defined
type. Is it possible ? :rolleyes:

Hi!

I guess the best you can do is to subclass a list. Here is a (quite silly) snippet. You can limit the size of the list, and it only accepts items which have the same type as the first item in the list:

class StrictList(list):
    def __init__(self, limit):
        list.__init__(self)
        self.limit = limit

    def add(self, item):
        if len(self) == self.limit:
            pass
        elif len(self) == 0:
            self.append(item)
        else:
            if type(item) == type(self[0]):
                self.append(item)
            else:
                print "Error! Item has wrong type"

# a list of hashes
hash_list = StrictList(5)
hash_list.add({"a":4})
hash_list.add({"b":3})
# string is not accepted -> error
hash_list.add("hello")
print hash_list

# list of strings
string_list = StrictList(3)
string_list.add("a")
string_list.add(4)
string_list.add("b")
print string_list

# list of integers
int_list = StrictList(3)
for i in range(10):
    int_list.add(i)
print int_list

Hope this helps a bit :)

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.