string - Confusion in file functioning and append function using Python -
i have 2 questions exam.
t2=("a","b","hello") alist=["barney",["wilma"]] print(alist[1].append(t2))
answer:
none
i thought [“wilma”,(“a”,”b”,”hello”)]
and
file has:
james,8,9 sonia,7,6 clark,4,5
code:
endofprogram=false try: infile=open("names.txt",”r”) except ioerror: print("error reading file") endofprogram=true if endofprogram==false: line in infile: line.strip('\n') alist=line.split(',') print(alist)
answer
['james','8','9\n'] ['sonia','7','6\n'] ['clark','4','5\n']
why '\n' still there? lastly:
def change(alist): alist=alist.pop() alist.append(5) return def main(): mylist=[1,2,[3]] change(mylist) print(mylist) main()
answer:
[1,2]
why answer? shouldn't [1,2,5]
?
list.append
in-place operation, modifies list in-place , returnsnone
.
>>> lst = [] >>> repr(lst.append(1)) #returns none 'none' >>> lst #list modified [1]
- strings immutable, need re-assign result of
.strip()
call variable.
line = line.strip('\n') #re-assign new returned string variable. alist = line.split(',')
- you re-assigned
alist
different list,.append()
call won't affect passed list.
def change(alist): alist = alist.pop() #now alist points [3] not `[1, 2, [3]]` alist.append(5)
you can use assignment statement here:
alist[-1] = 5
Comments
Post a Comment