Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python list comprehension by step of 2

Tags:

python

list

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

like image 306
jason Avatar asked Oct 19 '15 01:10

jason


People also ask

Is list comprehension in Python 2?

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.

Can you do list comprehension in Python?

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.


2 Answers

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]
like image 36
Ozgur Vatansever Avatar answered Oct 19 '22 19:10

Ozgur Vatansever


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']
like image 63
Alex Taylor Avatar answered Oct 19 '22 19:10

Alex Taylor