t2=("A","B","Hello")
alist=["Barney",["Wilma"]]
alist.append(t2)
print(alist.pop(1).extend(t2))
print(alist)
print((alist[1][2].upper()))
print(alist)
Hi guys. I just had a qs regarding tuples as I am new to python.
why does print(alist.pop(1).extend(t2))
give NONE on execution?
Why does print(a list)
below that give ['Barney', ('A', 'B', 'Hello')]
and not open tuple inside list as the function used is extend and not append?
alist=["Hello"]
t1=(1,2,[3,4],5,6)
t1[2].append(alist)
print(t1)
t1[2].pop().append(t1)
print(a list)
qs- Why does print(a list) in the end print ['Hello', (1, 2, [3, 4], 5, 6)]
? is it because the thing that is pooled in the previous sentence i.e. Hello is alist?
list.extend
extends the list in place (see the docs: http://docs.python.org/2/tutorial/datastructures.html) , and thus returns none. Rather than having a new variable with the extended list, your list with the new items is still called alist
alist prints ['Barney', ('A', 'B', 'Hello')]
, because that's what you've asked it to do.
Step by step,
t2=("A","B","Hello")
alist=["Barney",["Wilma"]]
alist.append(t2) # ['Barney', ['Wilma'], ('A', 'B', 'Hello')]
pop1 = alist.pop(1) # ['Wilma']
extend1 = pop1.extend(t2) #extend1 = None, pop1 = ['Wilma', 'A', 'B', 'Hello']
print(alist.pop(1).extend(t2)) # None
print(alist) #you've popped wilma, so the rest remains: ['Barney', ('A', 'B', 'Hello')]
As for third, this should be exactly the behavior you expect. First, you pop hello
from alist
, then you append all of t1
to the thing you just popped, namely hello
. So, ['Hello', (1, 2, [3, 4], 5, 6)] should be what you expected to get. Did you expect something different?
print(alist)
on the last line prints ['Hello', (1, 2, [3, 4], 5, 6)]
, because when you run t1[2].pop()
, what you get is a a reference to alist in particular, not an arbitrary list element. So then, the append(t1)
appends t1
to the actual alist, which you then print.