+ 4
Python: How do we deal with a list plus a string?
x = [] def af (b): x.append(b) return x def ab(f): f+="1" return f print(len(af(ab([1,0])))) #outputs 1 Specifically, I don't quite understand the line f+="1" when f is [1,0]. The function ab(f) gives us the output [1, 0, '1']. How come the double quotes in function ab(f) became single quotes? If we plug [1, 0, '1'] into function af(b), does it mean that there is ONE (nested) list in list x? Would this be the reason that the length of function af(b) is 1?
3 Answers
+ 9
There is no difference between double quote and single quote in python!
What is concatenation of a list with a string?
String can be considered as a list of character! So,
x = [1,2,3]
x += "abc"
print(x)
Will give: [1, 2, 3, 'a', 'b', 'c']
What is append function?
It is used to add a single element!
x = [1,2,3]
x.append(4)
print(x)
Output: [1,2,3,4]
Similarly,
x = [1,2,3]
x.append([1,2,3])
print(x)
Output: [1,2,3,[1,2,3]] and not [1,2,3,1,2,3]
Now,
ab function simply adds '1' to the list [1,0] and returns the new list formed i.e. [1,0,'1']
af function just appends the output of the ab function i.e. [1,0,'1'] to the list x (global)
So, here,
Simplified form of function af will be,
x = []
x.append([1,0,'1'])
print(x)
Output: [[1,0,'1']]
Of course, since x has only 1 element i.e. although a list but counts as a single element! So the length of x becomes 1
+ 7
x = []
def af (b):
x.append(b)
return x
def ab(f):
f+="1"
return f
print(len(af(ab([1,0]))))
A list [1,0] is used to call function ab(). The list is stored in f. In this function f+="1" append an additional element to list f, which will be returned to the caller. [1,0,"1]
Now function af() is called with the modified list that was returned from ab(). function af uses a defined list x and appends the list that is stored in b. The result is now a list in a list: [[1,0,"1"]]. Length of the list is 1 element, this will be printed.
+ 3
Solus , just to answer your question about single nad double quotes. In all data types and data structures that can held strings, when a new item that will added with double quotes, these will be changed to single quotes.
txt = "hello"
a = []
a.append(txt)
print(a) -> ['hello']