NewToJS
NewToJS

Reputation: 2101

Python: Best way to use a list comprehension?

I'm trying to use a list comprehension in python 2.7 to better achieve what I have now:

params['item1'] = request.GET.get('item1', '')
params['item2'] = request.GET.get('item2', '')
params['item3'] = request.GET.get('item3', '')
params['item4'] = request.GET.get('item4', '')
params['item5'] = request.GET.get('item5', '')

params['items'] = [
    params['item1'].encode('utf-8'),
    params['item2'].encode('utf-8'),
    params['item3'].encode('utf-8'),
    params['item4'].encode('utf-8'),
    params['item5'].encode('utf-8')
]

I'm wondering if a loop and list comprehension would work best (like below) But I'm also wondering if there are better ways to do this.

params['items'] = []

for x in range(5):
    item = 'item' + str(x+1)
    params[item] = request.GET.get(item, '')
    params['items'].extend(params[item].encode('utf-8'))

Upvotes: 0

Views: 60

Answers (2)

Acccumulation
Acccumulation

Reputation: 3591

Assuming params starts empty, I would split this into a dictionary comprehension and a list comprehension. I would also change the range rather than adding one to each index:

 params={'item' + str(x):request.GET.get('item' + str(x), '') for i in range(1,6)}`
 params['items']=[item.encode('utf-8') for item in params.keys()]

Something else to consider is if request.GET is creating an external call every time you access it. If so, you should create one local copy and access that, e.g.

local_copy = request.GET.copy()
params={'item' + str(x):local_copy.get('item' + str(x), '') for i in range(1,6)}`

Upvotes: 0

Prune
Prune

Reputation: 77900

Yes, a list comprehension would handle this neatly:

params["items" = [request.GET.get('item'+str(i), '').encode('utf-8')
                      for i in range(1,6) ]

"better" is a value judgment, which is out of scope for Stack Overflow. Is the list comprehension easier to read and maintain than your original loop? That's up to you and your programming/usage team.

Upvotes: 2

Related Questions