Why does this statement produce an error even though a string is actually a list of character constants?
string_name = ""
string_name.append("hello word")
The reason I expect this to work is because when we use for-loop, we are allowed to use this statement:
for i in string_name:
...
I think string_name
is considered as a list here(?)
That's what they teach you in an algorithms and data structures class, that deal with algorithmic languages (unreal) rather than real programming languages, in Python, a string is a string, and a list is a list, they're different objects, you can "append" to a string using what is called string concatenation (which is basically an addition operation on strings):
string_name = "hello"
string_name = string_name + " world"
print(string_name) # => "hello world"
Or a shorthand concatenation:
string_name = "hello"
string_name += " world"
print(string_name) # => "hello world"
Lists and strings belong to this type called iterable
. iterable
s are as they're name suggests, iterables, meaning you can iterate through them with the key word in
, but that doesn't mean they're the same type of objects:
for i in '123': # valid, using a string
for i in [1, 2, 3]: # valid, using a list
for i in (1, 2, 3): # valid, using a tuple
# all valid, all different types
I strongly recommend that you read the Python Documentation and/or take the Python's Tutorial.
From Docs Glossary:
iterable
An object capable of returning its members one at a time. Examples of iterables include all sequence types (such aslist
,str
, andtuple
) and some non-sequence types likedict
, file objects, and objects of any classes you define with an__iter__()
or__getitem__()
method. Iterables can be used in a for loop and in many other places where a sequence is needed (zip()
,map()
,…
). When an iterable object is passed as an argument to the built-in functioniter()
, it returns an iterator for the object. This iterator is good for one pass over the set of values. When using iterables, it is usually not necessary to calliter()
or deal with iterator objects yourself. The for statement does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. See also iterator, sequence, and generator. More about iterables.