I’m new to Python. Have been studying it with courses on udacity and now I am trying to do things to learn further more.
I’ve created this short code block:
list_a = []
list_b = []
for e in a_list:
list_a.append(e['a'])
list_b.append(e['b'])
list_b = set(list_b)
(list_a as well should not contain duplicates but it won’t be attempted in first place so no strict need of making it a set as well unless it makes the code better looking and easier to go through)
After looking at this code of mine, it does not seem elegant or Pythonic enough.
My question is, how should I reformat this? I would like to learn the good and right way of doing things.
My goal here is to go through a list called a_list, which contains
dictionaries as its items. Then for each item in the dictionary, add
the value of key ‘a’ to a new list called list_a, and do the same for
key ‘b’. However list of key ‘b’ should be a set and strictly not to
contain any duplicates.
Thank you.
While this does iterate over
a_listtwice, you can rewrite it like this:assuming Python 2.7 or later.
I’ve chosen the name
set_binstead oflist_bsince we’re doing a set comprehension, not a list comprehension in the second line.If you want to iterate over
a_listonly once, then you can at least skip one list creation: