I want to initialize a list in python. I do not understand why the code below does not work:
u = ['abc', 'de', 'fghi', 'jklm', 'n', '']
for item in u:
item = len(item)
There are other ways to initialize the list, like:
u = [len(item) for item in u]
But, my question is why the first code does not work.
Edit:
I am a newbie to Python, and programming. Unfortunately I do not understand some parts of your answers. For example:
- rebinding in "rebinding the name item
to the length of the name item
"
- iterator in "item" is a temporary variable that points to an element of a u
based on where the (implicit) iterator is pointing
As far as I understand, my second example, creates a new_list
in memory, and assigns the values of new_list
to u
. No matter what the previous values were. But I want to know how I can change the values, in the first list. Thanks
To initialize a class member variable, put the initialization code in a static initialization block, as the following section shows. To initialize an instance member variable, put the initialization code in a constructor.
Initialization lists allow you to choose which constructor is called and what arguments that constructor receives. If you have a reference or a const field, or if one of the classes used does not have a default constructor, you must use an initialization list.
Member initializer list is the place where non-default initialization of these objects can be specified. For bases and non-static data members that cannot be default-initialized, such as members of reference and const-qualified types, member initializers must be specified.
Static Data Member Initialization in C++ We can put static members (Functions or Variables) in C++ classes. For the static variables, we have to initialize them after defining the class. To initialize we have to use the class name then scope resolution operator, then the variable name. Now we can assign some value.
In the first case, you are not initializing anything. "item" is a temporary variable that points to an element of a u based on where the (implicit) iterator is pointing. If you want to initialize a list in the first style, you can do so as:
u = ['abc', 'de', 'fghi', 'jklm', 'n', '']
v = []
for item in u:
v.append(len(item))
print v
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With