avik
avik

Reputation: 271

Difference Between " " and [ ] in Python

I have written a simple program to reverse a string but I am getting different result with i write a = "" and when I write a = []. Please can someone help me explain why this happens:

Input is:

"Argument goes here"

1st way

 a= []
 for i in range(( len(text)-1,-1,-1):
   a+= text[i]  
 return a

Output is: ['e', 'r', 'e', 'h', ' ', 's', 'e', 'o', 'g', ' ', 't', 'n', 'e', 'm', 'u', 'g', 'r', 'A']

2nd way

a = ""
for i in range(1, len(text) + 1):
    a += text[len(text) - i]  
return a

Output is: ereh seog tnemugrA

Upvotes: 0

Views: 101

Answers (2)

hygull
hygull

Reputation: 8740

@avik, do not do in that way. You can use the below approach to reverse string.

[] denotes the empty list and "" denotes an empty string.

  1. In first case, you are adding each character of your string from end to list a using a += text[i]. So you got a list of characters. Here you can use ' '.join(a) to get a reversed string before returning a.

  2. In second case, you are concatenating each character of string from end so you got a reversed string.

Reverse string:

s = "Argument goes here"

reversed_s = "".join(list(reversed(s)))

>>> s = "Argument goes here"
>>>
>>> reversed(s)
<reversed object at 0x00000275F29B9F60>
>>> list(reversed(s))
['e', 'r', 'e', 'h', ' ', 's', 'e', 'o', 'g', ' ', 't', 'n', 'e', 'm', 'u', 'g', 'r', 'A']
>>>
>>> "".join(list(reversed(s)))
'ereh seog tnemugrA'
>>>

Upvotes: 1

jpp
jpp

Reputation: 164773

a = [] instantiates an empty list. When you add to a list with the + operator, you are performing a list extend. In other words, you are extending your list by the extra character. Note that since you are adding one character at a time, this has the same effect as list.append.

a = '' instantiates an empty string. When you add to a string with the + operator, you are performing a string concatenation.

The results will therefore be different. The first will give you a list object with reversed elements. The second will give you a str object with characters reversed.

Upvotes: 5

Related Questions