1

I came from C world where the size of buffers can be controlled in advance. For instance, declaring a buffer of doubles that holds 10 elements, we do:

double *buffer = calloc(10, sizeof(double));

In Python, it is quite the contrary in the sense that we don't need to worry about the details and the size of the buffer by saying buffer=[].

My question is: If I want to restrict a python list to hold an arbitrary number of values, say 10 doubles, how can we do that with default python lists or maybe numpy?

12
  • 1
    check out stackoverflow.com/questions/311775/… Commented Apr 18, 2018 at 20:52
  • I don't think this is a precise duplicate as user is open to numpy. Commented Apr 18, 2018 at 21:00
  • I fail to see how this is a duplicate of the linked question. Initializing to a length and actually restricting the length are not the same thing. Commented Apr 18, 2018 at 21:28
  • @jpp I added another to the dupe list with the same C foreword even. Commented Apr 18, 2018 at 21:28
  • @PaulPanzer Did you see the second duplicate in the list there? Commented Apr 18, 2018 at 21:29

2 Answers 2

2

To ensure an array is of a fixed size and of a certain type, you should use numpy. This is true even with non-numeric data.

Some examples are below.

import numpy as np

arr = np.zeros(10, dtype=float)
# array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]), dtype = float64

arr = np.zeros(10, dtype=int)
# array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), dtype = int32

arr = np.empty(10, dtype='<U8')
# array(['', '', '', '', '', '', '', '', '', ''],
#       dtype='<U8')
Sign up to request clarification or add additional context in comments.

Comments

1

You can use deque from collections that has a maxlen property.

from collections import deque
d = deque(maxlen=2)

You can then append, pop, iterate or do whatever you want with your restricted list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.