xlabels = ["first", "second", "third", "fourth"]
Is there a way to step through a list comprehension by 2?
for i in range(0,len(xlabels)):
xlabels[i]=""
becomes ["" for i in xlabels]
It turns the list into blanks. output: ["","","",""]
what about?:
for i in range(0,len(xlabels),2):
xlabels[i]=""
I want to turn every other item in the list into a blank. output: ["", "second", "", "fourth"]
List comprehensions, a shortcut for creating lists, have been in Python since version 2.0. Python 2.4 added a similar feature – generator expressions; then 2.7 (and 3.0) introduced set and dict comprehensions.
One main benefit of using a list comprehension in Python is that it's a single tool that you can use in many different situations. In addition to standard list creation, list comprehensions can also be used for mapping and filtering. You don't have to use a different approach for each scenario.
You are on the right track by using range()
with step. List comprehensions tend to create a new list instead of modifying the existing one. However, you can still do the following instead:
>>> xlabels = [1, 2, 3, 4]
>>> [xlabels[i] if i % 2 != 0 else '' for i in range(len(xlabels))]
['', 2, '', 4]
Personally, I'd use a list slice and list comprehension together:
>>> full_list = ['first', 'second', 'third', 'fourth', 'fifth']
>>> [element for element in full_list[::2]]
['first', 'third', 'fifth']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With