-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
  • 473
  • 1
  • 4
  • 16

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
  • 162,537
  • 44
  • 333
  • 446
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
  • 15,737
  • 15
  • 35
  • 52
0
a = []

if not a:
   a.extend(["" for _ in range(68)])
adrtam
  • 6,525
  • 2
  • 10
  • 26
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,004
  • 2
  • 18
  • 29