What's an elegant way to test for list index existing?

Peter Otten __peter__ at web.de
Sun Sep 30 04:03:41 EDT 2018


Glen D souza wrote:

> fld = [ ]
> data = shlex.split(ln)
> for item in data:
>        fld.append(item)
> fld = fld + [0] * (5 - len(data))

There's no need to make a copy of data, one item at the time.
It's a tedious way to build a new list, and you are throwing it away in the 
next line anyway, as adding first_list + second_list creates a new list 
containing the items of both.

So:

data = shlex.split(ln)
fld = data + [""] * (5 - len(data))  # the OP wants strings





More information about the Python-list mailing list