Add values in a list

Asked

Viewed 1,928 times

-3

In python, when printing a certain variable (after a loop) I get as a result:

[3]

[7]

[13]

[4]

values are within a variable a . Hence when I make list.append(a) and print, I have: [3]

[3,7]

[3,7,13]

[3,7,13,4]

And what I need is a list of the kind:

list= [3,7,13,4]

how can I do this?

2 answers

1

Using the append method of the Array you add elements at the end of your list.

lista = [];

lista.append(3);

lista.append(7);

lista.append(13);

lista.append(4);

print(lista);
  • doesn’t work like this because when printing it leaves wrong

  • How’s the current code? Update the question about what code looks like you want.

1

By complementing the @Viniciusfarias comment, if you want to add multiple items from one list to another list at a time, you can use the method .extend(). Its use would be something like:


lista = [3, 7, 13, 4]
lista2 = [5, 8]
lista.extend(lista2)

print(lista)
# [3, 7, 13, 4, 5, 8]

To learn all the methods, visit official documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.