[Tutor] Is there a better way to write my code?

Alan Gauld alan.gauld at yahoo.co.uk
Tue Aug 14 04:03:44 EDT 2018


On 14/08/18 07:56, Rafael Knuth wrote:

> List comprehension is really cool. One thing I like about list
> comprehension is that you can get a dictionary, tuples or lists as a
> result by just changing the type of braces.
> 
> # dictionary
> colors = ["red", "blue", "white", "yellow"]
> colors_len = [{color, len(color)} for color in colors]
> print(colors_len)

Actually, these are sets not dictionaries. A dictionary would
have pairs separated by a colon, a set just has single values
separated by commas. They both use {}.

However List comprehensions are a special subset of a more
general construct called a generator expression and with
those you can build dictionaries:

colors = ["red", "blue", "white", "yellow"]
colors_len = dict( (color, len(color)) for color in colors] )
print(colors_len)

> # tuples
> colors = ["red", "blue", "white", "yellow"]
> colors_len = [(color, len(color)) for color in colors]
> print(colors_len)

This gives a list of tuples, but you can use a gen exp to
create a tuple of tuples:

colors_len = tuple((color, len(color)) for color in colors)

> # lists
> colors = ["red", "blue", "white", "yellow"]
> colors_len = [[color, len(color)] for color in colors]
> print(colors_len)

So many choices :-)

> Can you shed some light on when to use which of the above data structures?
> I assume there is no simple answer to that question, 

Correct, it all depends on the nature of the data and
what you plan on doing with it. But there are some
general guidelines for collections:

- Use a list for objects(*) where you might need to
  change the value of one of the objects

- Use a tuple for objects where you don't need
  to change the values (it remains the same during
  the life of the program).
- Use a tuple if you want to use the collection as
  a key in a dictionary.

- Use a set where you want to eliminate duplicates

- Use a dict where you want direct access to an
  object based on some unique characeristic.

- Use a class where you have objects that
  you need to manipulate in different ways.
  ie. there is functionality associated with the data.

(*) Bearing in mind that an "object" can itself
    be a list/tuple/dict etc

So, for your example, the dictionary is probably
the most useful structure since you can access
the length of any string by looking up the string:
eg.
print(color_len['blue'])


-- 
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