[Tutor] Updating index of a list

Alan Gauld alan.gauld at btinternet.com
Fri Oct 9 00:17:58 CEST 2015


On 08/10/15 20:40, Andrea Nguy wrote:

> What’s happening is that I am trying to take a list of a list as such:

[['1', ' james', ' 1', ' 90'],
  ['2', ' alice', ' 1', ' 95'],
  ['5', ' jorgen', ' 1', ' 99’]] (it continues) from a text file.

When you say from a text file, do you mean you are reading the
values in and converting them to the appropriate types? Or are
you just adding them directly to the list? In which case they
will all be strings?

> However, what I am trying to do take the indexes of thelist[0][1]
 > and thelist[0][3] and times them by a float number
 > - returning the list with all of the values multiplied according to 
the float.

> Is this possible?

Yes of course.

just use a for loop like this:

for sublist in thelist:
     sublist[0] *= someFloat
     sublist[3] *= someFloat

Which changes the values in place.

Or a little more advanced you can use a list comprehension:

newlist = [[sub[0]*someFloat, sub[1],[sub[2],sub[3]*someFloat]
             for sub in thelist]

Which will create a new list with the values you desire
leaving the original list unchanged.

> would it be easier if I tried to change the list of the
 > list into a dictionary for efficiency?

While changing data type is often the right thing to do to
make the code clearer, thinking about efficiency before
you know you have a problem is nearly always the wrong
thing to do.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list