Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializing members of a list

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

like image 645
Ali Avatar asked Sep 03 '13 23:09

Ali


People also ask

How do you initialize a member variable?

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.

When must you use a member initializer list?

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.

What is member initializer list in OOP?

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.

How do you initialize a data member in C++?

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.


1 Answers

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
like image 102
Manoj Pandey Avatar answered Oct 30 '22 02:10

Manoj Pandey