1
# 1st Method
a = ["b","x","k"]
a += "5"
print(a)

# 2nd Method
def add1(new):
    a.append(new)

add1("X")
print(a)

# 3rd Method
def add2(new):
    a += new

add2("Z")
print(a)

Function add2 looks almost similar to the 1st method in adding an item into a list, yet it produces an error "local variable referenced before assignment". What is the logic behind this error? How do we fix the error for function add2 without declaring variable 'a' as global?

waiwai57
  • 35
  • 4

2 Answers2

0

For lists, += extends. You can use a.extend(new).

timgeb
  • 76,762
  • 20
  • 123
  • 145
  • 1
    That does not refer to the problem described in the question though (title and body). –  Feb 02 '22 at 11:19
  • @bbbbbbbbb why not? – timgeb Feb 02 '22 at 11:19
  • 1
    Oh, actually it does (well, it works around it). Sorry! –  Feb 02 '22 at 11:20
  • Ehhh... I think O.P. (incorrectly) expected the += to be shorthand for append and this only really works here by accident. Because 1-element strings are iterable and the behavior _happens_ to be the same as an append here. – wim Feb 02 '22 at 11:27
-1

Add another parameter to your function and pass the list through that.

 a = ["b", "x", "k"]
    a += "5"
    print(a)
    
    
    # 2nd Method
    def add1(new):
        a.append(new)
    
    
    add1("X")
    print(a)
    
    
    # 3rd Method
    def add2(list_to_add, new):
        list_to_add += new
    
    
    add2(a, "Z")
    print(a)
Raed Ali
  • 549
  • 1
  • 6
  • 22