-1

I am extracting values from excel into a list but some of them are blank.

I want to check if the list is empty, and if empty insert 68 empty strings. Is there a way to do that?

a = []

if not a:
   #enter 68 empty strings into a. eg: a = ['', '', '',....]
edcoder
  • 503
  • 1
  • 5
  • 19

4 Answers4

3

Python lets you multiply a list with a number to repeat it:

a = [''] * 68

If you also have other references to this list, so you actually need to update the same list instead of creating an new one, use extend:

a.extend([''] * 68)
Thomas
  • 174,939
  • 50
  • 355
  • 478
2

Using the logical or operator, you can avoid conditions to create the list with empty strings, or keep the original list in case it was not empty:

a = a or [''] * 68
  • If a is empty, then it's falsey so the or will return the second argument.
  • If a is not empty, it is truthy so the or will return it.
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
0
a = []

if not a:
   a.extend(["" for _ in range(68)])
adrtam
  • 6,991
  • 2
  • 12
  • 27
0

Suppose you have a list a, and we want to insert n=68 blank strings at position i

a = [1, 2]
i = 1
n = 68
result = a[:i] + [''] * n + a[i:]

Then of course you can set a = result if you wanted to modify a directly. This is of course overkill, as you don't really want to insert into an existing list, this time, but I thought I'd answer the question asked.

Kenny Ostrom
  • 5,639
  • 2
  • 21
  • 30