Viorel
Viorel

Reputation: 39

How to declare an array as a function parameter in Python?

I have declared an empty list. I want to store in that one some strings from a text file. If I am doing without creating TXT_to_PList it is working smoothly. But using TXT_to_PList length of deTrimis array will be 0. Why?

deTrimis = []

def TXT_to_PList(fileName,array):
    with open(fileName) as f:
        array = f.read().splitlines()
TXT_to_PList('strings.txt',deTrimis)
print (len(deTrimis))

Upvotes: 1

Views: 103

Answers (2)

Peter
Peter

Reputation: 12375

You don't need that empty list at all:

def TXT_to_PList(fileName):
    with open(fileName) as f:
        return f.read().splitlines()

deTrimis = TXT_to_PList('strings.txt')

Upvotes: 1

RafalS
RafalS

Reputation: 6344

You can't modify function argument by assignment, change it to:

array.extend(f.read().splitlines())

see more info here: Why can a function modify some arguments as perceived by the caller, but not others?

Upvotes: 0

Related Questions