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

Glen D souza glenpop54 at gmail.com
Sat Sep 29 01:45:50 EDT 2018


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


On Sat, 29 Sep 2018 at 11:03, Glen D souza <glenpop54 at gmail.com> wrote:

> i have a approach, it may not be best
>
> fld = [ ]
> for data in shlex.split(ln):
>        fld.append(data)
>
>
>
> On Sat, 29 Sep 2018 at 07:52, <jladasky at itu.edu> wrote:
>
>> On Friday, September 28, 2018 at 11:03:17 AM UTC-7, Chris Green wrote:
>> > I have a list created by:-
>> >
>> >     fld = shlex.split(ln)
>> >
>> > It may contain 3, 4 or 5 entries according to data read into ln.
>> > What's the neatest way of setting the fourth and fifth entries to an
>> > empty string if they don't (yet) exist? Using 'if len(fld) < 4:' feels
>> > clumsy somehow.
>>
>> How about this?
>>
>> from itertools import chain, repeat
>> temp = shlex.split(ln)
>> fld = list(chain(temp, repeat("", 5-len(temp))))
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>>
>



More information about the Python-list mailing list