0
# Function to convert   
def listToString(s):  
    
    # initialize an empty string 
    str1 = ""  
    
    # traverse in the string   
    for ele in s:  
        str1 += ele   
    
    # return string   
    return str1  
        
        
# Driver code     
s = ['Geeks', 'for', 'Geeks'] 
print(listToString(s)
Barmar
  • 741,623
  • 53
  • 500
  • 612
Ahmad
  • 1
  • 2
    str1 += ele is shorthanf for str1 = str1+ele. Each time a nez string is created and assigned to str1. – kubatucka Jun 29 '20 at 16:05

2 Answers2

0

It's not mutating the string.

str1 += ele

is equivalent to

str1 = str1 + ele

This creates a new string, it doesn't modify the existing string in place. You can see this if you do:

str1 = "xxx"
str2 = str1
str1 += "yyy"
print(str1, str2)

This will print xxxyyy xxx

There is some internal optimization in CPython that will reuse the memory if possible. See Python string concatenation internal details. But this is undetectable because it only takes place when there's one reference to the string. So in the above example, the optimization is prevented because str1 and str2 both refer to the original string; a copy of the string will have to be made when concatenating.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

As mentioned in other posts, str += ele creates a new string instead of changing the old one. You can see this by looking at the id of the object. I changed your code slightly to clarify:

# Function to convert
def listToString(s):
    # initialize an empty string
    str1 = ""

    # traverse in the string
    for i in range(len(s)):
        print("id of str1: {}".format(id(str1)))
        print("id of s: {}".format(id(s)))
        str1 += s[i]
        s[i] = i

    print(s)

    # return string
    return str1
# Driver code
s = ['Geeks', 'for', 'Geeks']
print(listToString(s))

which gives as output:

id of str1: 140451112373360
id of s: 140451111710920
id of str1: 140451111354016
id of s: 140451111710920
id of str1: 140451110861808
id of s: 140451111710920
[0, 1, 2]
GeeksforGeeks

As you can see, the id of the list never changes, because it's the same object. On the other hand, the id of str1 does change.

Johan
  • 80
  • 6