CodeBlessU
learn code with examples

Python Append element

Use .append() method to add one item at end of mutable sequence (List / Array / String). See How to append to tuple (immutable).

Argument is mandatory.

Syntax:
variable.append(new_item)
Return Value:
no return value
Use
  • Replace/Update - to update value at existing position.
  • Append - to add new element at end (Single).
  • Extend - to add new elements at end from iterable source (Single / Multiple).
  • Insert - to insert new element at start / middle (Single).

TypeError: append() takes exactly one argument

Why this error:

Are you trying to call .append() without any argument or multiple arguments?

Solution:

Call .append() with one argument.

List append at end

# Example, list append element
a1 = [10, 20, 30, 40, 50]

a1.append(60)
print(a1) # [10, 20, 30, 40, 50, 60]

TypeError: append() takes exactly one argument

# Example, list append raises TypeError
a1 = [10, 20, 30, 40, 50]

a1.append() # raises TypeError: append() takes exactly one argument

Tuple append at end

Tuple once created, can not be modified. But, two tuple can be added/concatenated to create another tuple. Use + operator to concatenate tuples.

Open Thoughts: Are you finding frequent need to append tuple? Would it be helpful to change its data type?

# Example, append element in tuple, concatenate
a1 = (1,2,3,4)

# append element 5
a1 = a1 + (5, )
print(a1) # prints (1, 2, 3, 4, 5)

Array append at end

# Example, Array append element
import array
a1 = array.array('l', [10, 20, 30, 40, 50] )

a1.append(60)
print(a1) # array('l', [10, 20, 30, 40, 50, 60])

TypeError: append() takes exactly one argument

# Example, Array append raises TypeError
import array
a1 = array.array('l', [10, 20, 30, 40, 50] )

a1.append() # raises TypeError: append() takes exactly one argument

In this page...

Copyright © All rights reserved.