CodeBlessU
learn code with examples

Python Extend elements

Use .extend() method to add items from other iterable source (i.e. list / array / tuple / string) to mutable sequence (List / Array / String). See How to extend to tuple (immutable).

Argument is mandatory.

Syntax:
variable.extend(iterable)
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 front / middle (Single).

TypeError: object is not iterable

Why this error:

Are you trying to append single element?
Are you trying to extend from non-iterable source?

Solution:

Use append() to add single element from non-iterable source. OR
Use iterable (i.e. list / array / tuple / string) source.


TypeError: extend() takes exactly one argument

Why this error:

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

Solution:

Call .extend() with one argument.

List extend

# Example, list extend elements
a1 = [10, 20, 30, 40, 50]
a2 = ["Hi", "There"]

a1.extend(a2)
print(a1) # [10, 20, 30, 40, 50, 'Hi', 'There']

# Example, extends single element (list contains one element)
a3 = ["Greetings"]
a1.extend(a3)
print(a1) # [10, 20, 30, 40, 50, 'Hi', 'There', 'Greetings']

# Example, string is iterable, contains four elements
a1.extend("Test")
print(a1) # [10, 20, 30, 40, 50, 'Hi', 'There', 'Greetings', 'T', 'e', 's', 't']

TypeError: 'int' object is not iterable

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

a1.extend(0) # raises TypeError: 'int' object is not iterable

TypeError: extend() takes exactly one argument

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

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

Tuple extend

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

# Example, Tuple extend elements
a1 = (1,2,3,4)
a2 = [5,6,7]

a3 = a1 + tuple(a2)
print(a3) # prints (1, 2, 3, 4, 5, 6, 7)

Array extend

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

a2 = (60, 70)

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

# Example, extends single element (Array contains one element)
a3 = [80]
a1.extend(a3)
print(a1) # array('l', [10, 20, 30, 40, 50, 60, 70, 80])

TypeError: 'int' object is not iterable

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

a1.extend(90) # raises TypeError: 'int' object is not iterable

TypeError: extend() takes exactly one argument

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

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

In this page...

Copyright © All rights reserved.