Create an empty list in python with certain size

后端 未结 15 1743
有刺的猬
有刺的猬 2020-11-22 12:00

I want to create an empty list (or whatever is the best way) that can hold 10 elements.

After that I want to assign values in that list, for example this is supposed

15条回答
  •  感动是毒
    2020-11-22 12:07

    (This was written based on the original version of the question.)

    I want to create a empty list (or whatever is the best way) can hold 10 elements.

    All lists can hold as many elements as you like, subject only to the limit of available memory. The only "size" of a list that matters is the number of elements currently in it.

    but when I run it, the result is []

    print display s1 is not valid syntax; based on your description of what you're seeing, I assume you meant display(s1) and then print s1. For that to run, you must have previously defined a global s1 to pass into the function.

    Calling display does not modify the list you pass in, as written. Your code says "s1 is a name for whatever thing was passed in to the function; ok, now the first thing we'll do is forget about that thing completely, and let s1 start referring instead to a newly created list. Now we'll modify that list". This has no effect on the value you passed in.

    There is no reason to pass in a value here. (There is no real reason to create a function, either, but that's beside the point.) You want to "create" something, so that is the output of your function. No information is required to create the thing you describe, so don't pass any information in. To get information out, return it.

    That would give you something like:

    def display():
        s1 = list();
        for i in range(0, 9):
            s1[i] = i
        return s1
    

    The next problem you will note is that your list will actually have only 9 elements, because the end point is skipped by the range function. (As side notes, [] works just as well as list(), the semicolon is unnecessary, s1 is a poor name for the variable, and only one parameter is needed for range if you're starting from 0.) So then you end up with

    def create_list():
        result = list()
        for i in range(10):
            result[i] = i
        return result
    

    However, this is still missing the mark; range is not some magical keyword that's part of the language the way for and def are, but instead it's a function. And guess what that function returns? That's right - a list of those integers. So the entire function collapses to

    def create_list():
        return range(10)
    

    and now you see why we don't need to write a function ourselves at all; range is already the function we're looking for. Although, again, there is no need or reason to "pre-size" the list.

提交回复
热议问题