0

Hello I'm trying to improve the performance of my code (find out a nice article here: http://leadsift.com/loop-map-list-comprehension/ )

And I'd like to know if I can use a comprehension list in this part of my code:

for fmt in excels:
    xls_list.add(fmt)
    df_dict[fmt] = ''
PenDragon
  • 13
  • 4
  • 2
    Why do you think list comprehension will improve performance? – Maroun Oct 18 '17 at 07:19
  • Because one action is appending elements to a list, maybe I can improve this functionality. In the other hand I'm creating new keys in my dict so I'm not pretty sure if it's a good idea or not. – PenDragon Oct 18 '17 at 07:23
  • A list comprehension can give a slight speed-up compared to a "traditional" `for` loop, but the difference isn't as great in Python 3. However, your code does not look suitable for a list (or other) comprehension. – PM 2Ring Oct 18 '17 at 07:23
  • 1
    Your code is readable, don't ruin it and attempt to "one-line" everything. – Maroun Oct 18 '17 at 07:23
  • Ok thanks, for the advice. I will consider using comprehension list if I only have one loop appending elements. – PenDragon Oct 18 '17 at 07:26
  • What is `xls_list`? `list`s have no `.add()` method. – Adirio Oct 18 '17 at 07:26
  • Python lists don't have an `.add` method, but sets do. Is `xls_list` actually a set? If you want to quickly create a dictionary from a sequence of keys, with all the values set to `''`, take a look at `dict.fromkeys`. – PM 2Ring Oct 18 '17 at 07:26
  • It's really a set because I want unique elements, but after processing the file I cast set to list for making other operations. – PenDragon Oct 18 '17 at 07:28
  • Is `excels` a list as in my answer? because you need no iteration nor comprehension for that then. If not provide an example of `excels` with a low number of elements (2 at least) – Adirio Oct 18 '17 at 07:32
  • Your title and body seem a bit inconsistent with each other. In regards to the title, have a read at [Python List Comprehension Vs Map](https://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map). – Reti43 Oct 18 '17 at 08:09
  • Yes, @Adirio thanks for your answer. – PenDragon Oct 18 '17 at 08:15
  • @Reti43 Maybe it's a bit inconsistent, I'll take a look to that reference. Thanks – PenDragon Oct 18 '17 at 08:17

1 Answers1

1
excels = ['1.xls', '2.xls']
xls_list = set()
for fmt in excels:
    xls_list.add(fmt)
    df_dict[fmt] = ''

could be trasnformed into:

xls_list = set(excels)
df_dict = dict.fromkeys(excels, '')
Adirio
  • 5,040
  • 1
  • 14
  • 26