Home > Mobile >  How to append values to list?
How to append values to list?

Time:05-13

I want to append my list with values for each loop iteration:

        for i in range (4,10):
        a_list = [1,2,3]
        a_list = a_list.append(i)

The wanted output would be [1,2,3,4,5,6,7,8,9]. But I get None. Also printing type(a_list) after using .append() gives me <class'NoneType'>. What is the problem here ?

CodePudding user response:

firstly, you have to mention a_list before for. instead, you will get [1, 2, 3, 9]. secondly, you give the a_list a value of a_list.append() function.

a_list = [1, 2, 3]
for i in range(4, 10):
    a_list.append(i)

CodePudding user response:

it is mainly because of the fact that list.append method does not return anything, it appends the given value to the list in-place.

we can confirm this by the simple example below

a = list()
b = a.append(5)
>> print(b)
None
>> print(a)
[5]

As matter of fact,there is a simpler and more performant way to achieve this

>> a_list = [1,2,3]
>> a_list  = list(range(4, 10))
>> print(a_list)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Here, we first shape a new list from a iterator range(4, 10), then we concate the two list together to get the list we want by adding the new list to the original list a_list.

by doing this, we can avoid the overhead caused by repeatedly call the list.append method in a for loop

CodePudding user response:

a_list = []
for i in range (1,10):
    a_list.append(i)

print(a_list)

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9]

You have the wrong indentation on the loop.You need to add i at each iteration. Also, to get the list you want, you need to add 1, then 2, then 3, and so on. i this is what needs to be added. Put print(i) and print each iteration.

a_list = [1,2,3]
for i in range (4,10):
    a_list.append(i)

print(a_list)

If you use your option, it will be correct to declare an array once. And then only add values. See below.

[1, 2, 3, 4, 5, 6, 7, 8, 9]
  • Related