0
How do you set the length of a list (defined, for example, as "array") in Python?
For example, Java allows you to define an array (which I would say is equivalent to a Python list) as follows: "int[] array = new int[desired-length];". In Python, however, I have not found a way to do this right off the bat. I have to either define each item right away, or for-loop my way through adding items to the end. Can I define the length right away, and THEN for-loop my way through (in my case, I'm trying to assign each item a random integer value), giving each item the random value?
5 ответов
+ 12
In Python there is no actual need or reason to define lists (or any mutable variables) with pre-set sizes. Only immutable ones kind of have to, as you declare them as constant for the runtime.
Still, if you need to instantiate a list of a given dimension you can use a list expression to do that, like:
l = [None for i in range(20)]
or simply:
l = [None] * 20
+ 12
On the other hand, if you need an array type - you can use Python numpy module, which supports array-like tensors (they are still called arrays though :)
import numpy as np
a = np.empty(20) # will create an array of size (20,) with an interesting value representation of "emptiness" ;)
+ 1
Kuba Siekierzyński... in the fitst 2 examples i get a list with 20 None items inside?
in your, 3rd example i get a list of "interesting value representations " as you called them. Just wanna make sure if this is right or am i doing something wrong?
+ 1
Theuns Booysen, he was using "None" as filler code. What he means is that you can fill it with whatever you want. In my case, I was filling the array with random integers.
+ 1
Thanks, was playing with the code and i figured it out!!! Thanks for bringing up the question and helping me to learn!!!