Append or Add to string of specific index
<p>I have a list of class objects 'x'. I am trying to create a new list by appending certain attribute values of the objects but I would like to append more that one attribute per index. For example, what I currently get:</p>

<pre><code>x = blah.values()

newList = []
for i in range(len(x)):
    if x[i].status == 'ACT':
        newList.append(str(x[i].full_name)),
        newList.append(str(x[i].team))
else:
    pass

print newList
</code></pre>

<p>The above code provides me with something like:</p>

<pre><code>['Victor Cruz', 'NYG', 'Marcus Cromartie', 'SF',....]
</code></pre>

<p>What I am trying to get:</p>

<pre><code>['Victor Cruz NYG', 'Marcus Cromartie SF',....]
</code></pre>

<p>How can I append more than one attribute per index? Hope this make sense, I can try to further elaborate if needed, thanks!</p>

<p>You could put the items into one string using <code>.format()</code> and <code>append</code> the string once:</p>

<pre><code>for i in range(len(x)):
    if x[i].status == 'ACT':
        newList.append('{} {}'.format(x[i].full_name, x[i].team))
</code></pre>

<hr>

<p>On a lighter note, using a <em>list comprehension</em> is a great alternative for creating your list:</p>

<pre><code>newList = ['{} {}'.format(o.full_name, o.team) for o in blah.values() if o.status == 'ACT']
</code></pre>

<p>You'll notice that <code>range</code> and <code>len</code> are no longer used in the comprehension, and there is no longer need for <em>indexing</em>.</p>

python python-2.7