How to Append to the End of an Empty List

Why does x = x.append(...) not work in a for loop?

append actually changes the list. Also, it takes an item, not a list. Hence, all you need is

for i in range(n):
list1.append(i)

(By the way, note that you can use range(n), in this case.)

I assume your actual use is more complicated, but you may be able to use a list comprehension, which is more pythonic for this:

list1 = [i for i in range(n)]

Or, in this case, in Python 2.x range(n) in fact creates the list that you want already, although in Python 3.x, you need list(range(n)).

How to append elements from input to empty list in python

I think it is better to use a list of dictionaries instead of a list.

Instead of this:

    pp = ["passangers:"]
passangerInput = input("what is your passanger name?")
if passangerInput:
pp.append()

print(passanger_list)

I would do:

passenger_list = []

def add_passenger(passenger_name):
if passanger_name:
passenger_list.append({"name":passenger_name})

add_passenger("bob")
print(passanger_list)

This way you can store multiple passengers and can even add other key-value pairs like seat number or class etc.

The way you are doing it will make it harder to retrieve information.

getting empty list even though appending while using recursion

You have fallen prey to one of the classic Python errors. You are passing [] into the function as t. You then modify t, and pass t into the recursive call. That means there is ONLY ONE LIST t. When you do proc.append(t), you are not grabbing a snapshot of the array. You are appending multiple references to that one list. By the time the function ends, t is empty, so your proc has multiple references to an empty list.

The short term fix is to change to

    proc.append( t.copy() )

or

    proc.append( t[:] )

how to append an element to a list without keeping track of the index?

There is a function called append:

ans <- list()
for (i in 1992:1994){
n <- 1 #whatever the function is
ans <- append(ans, n)
}

ans
## [[1]]
## [1] 1
##
## [[2]]
## [1] 1
##
## [[3]]
## [1] 1
##

Note: Using apply functions instead of a for loop is better (not necessarily faster) but it depends on the actual purpose of your loop.

Answering OP's comment: About using ggplot2 and saving plots to a list, something like this would be more efficient:

plotlist <- lapply(seq(2,4), function(i) {
require(ggplot2)
dat <- mtcars[mtcars$cyl == 2 * i,]
ggplot() + geom_point(data = dat ,aes(x=cyl,y=mpg))
})

Thanks to @Wen for sharing Comparison of c() and append() functions:

Concatenation (c) is pretty fast, but append is even faster and therefor preferable when concatenating just two vectors.

Adding an element to the end of a list in Scheme

A list is a chain of pairs. The elements are the cars of each pair, the cdr is a reference to the next pair in the chain, or an empty list for the last pair in the chain.

When you use (cons 'a '(b c)) you create a new pair in front of the existing list (b c), so the result is still a list.

But when you use (cons '(b c) 'a), you're creating a pair whose cdr is the symbol a, not a list. And the last pair in the list (b c) still has its cdr pointing to the empty list.

You need to copy the first list, and when you get to the end, you have to make the cdr point to a list containing a. You can do this with a recursive procedure.

(define (list-append old-list new-el)
(if (null? old-list)
(list new-el)
(cons (car old-list)
(list-append (cdr old-list) new-el))))
(list-append '(b c) 'a)

The logic is:

  • If we try to append to an empty list, just return a list containing the new element
  • Otherwise, append the new element to the tail of the original list with the recursive call, and then put the first element in front of that (using the (cons new-element old-list) method that you showed in your first example).

Adding values to an empty 2D list (TypeError)

You have many mistakes in this code.

The values_to_go list is not a 2d list. The (7) or any number between parentheses is totally equal to a number without any parentheses. If you want to make it a tuple, you should tell python that these are not parentheses around the number; but these are tuple signs. So 7 is totally equal to (7). You should use (7,) to tell python that this is a tuple with one member which is 7. So this ... = values_to_go[i][0] will be OK.

Another mistake is the part that you've written to append members into the empty list. You cannot point to a non-existent member of a list with this expression: list[i][0]. There is no list[i] and therefore obviously there is no list[i][0]. If you want to append into the end of the list, you should just do it:

list.append(anything)

This would be something like this:

>>> values_to_go = [(7,), (8,), (9,)]  # or [[7], [8], [9]]
>>> some_list = []
>>> for i in range(len(values_to_go)):
... some_list.append(values_to_go[i][0])
...
>>> print(some_list)
[7, 8, 9]

>>> # and if you want to make it 2D:
>>> some_list = []
>>> for i in range(len(values_to_go)):
... some_list.append([values_to_go[i][0]])
...
>>> print(some_list)
[[7], [8], [9]]

How to append an empty list in a for loop in Python and i got None when try to append the reversed string.Why its showing None?

string = "Hi how are you"
reversedString = []
mysplit = string.split(" ")

for i in mysplit:
reverse = i[::-1]
reversedString.append(reverse)

print reversedString

output:

['iH', 'woh', 'era', 'uoy']

Scheme - Appending to the end of a list

You just need to end the recursion with a list, not an item. Instead of this:

(if (null? lst)
item

Do this:

(if (null? lst)
(list item)

To clarify - a list in Scheme must end in the empty list '(). If your recursion ends with an item, you'll get something like this in the end:

(cons 4 5)
=> '(4 . 5)

That's a cons pair. A proper list ends in the empty list:

(cons 4 (cons 5 '()))
=> '(4 5)

Which is the same as:

(cons 4 (list 5))
=> '(4 5)

By the way, this is the idiomatic way to append an item at the end:

(define (my-append lst item)
(append lst (list item)))


Related Topics



Leave a reply



Submit