Python Error's when I try to optimize those lines of code
<p>I use python 2.7, I want to reduce and optimize this code lines but I have a problem, could anybody help me please? </p>

<p>I have this list <code>B = [[0, Act1, XX1, u'P-Um'],.....[0, Act100, ZZ30, u'D- MOM']]</code> </p>

<ol>
<li>I want to take only the 4th value from B </li>
<li>Take just the part after hyphen and the space which is sometimes</li>
<li>Bring back to B</li>
</ol>

<p>Right now I wrote this code </p>

<pre><code>for i in range(len(B)):
        x.append(B[i][3])
        A = [i.split('-',1)[1] for i in x]  
        #A=[u'Um', u' LY', u' NO', ......, u' MOM']               
    for i in range(len(B)):
        A[i].lstrip()
        p = []
        for i in range(len(B)):
            p.append(A[i].lstrip())
        for i in range(len(B)):
            B[i][3] = p[i]
</code></pre>

<p>When I try to make it shorter at follows I have two errors.</p>

<pre><code>#Short version

for i in range(len(B)):
        x.append(B[i][3])
        A = [i.split('-',1)[1], x] #Error:AttributeError: 'int' object has no           attribute 'split'
        B[i][3].append(A[i].lstrip()) #Error:AttributeError: 'unicode' object has no attribute 'append'
</code></pre>

<p>I try many ways to solve the errors but still not working. Could you help please? Do you think is possible to make the top part shorter without errors?</p>

<p>Thank you very much in advance.</p>

<p>I'm not seeing the many ways you've tried, but your code does have a handful of missteps. Even after correcting the indentation errors, your first variant iterates over an index which you don't need four times, and strips every entry twice (only using the result the second time). The second version fails firstly because that index isn't the entry and secondly because you're trying to alter a string instead of replacing it. </p>

<pre><code>A=[]
x=[]
for Bi in B:
    Bi3 = Bi[3]
    part = Bi3.split('-',1)[1].lstrip()
    x.append(Bi3)       # Original B[i][3] data
    A.append(part)      # What is this for?
    Bi[3] = part        # replaces B[i][3]
</code></pre>

<p>If you actually need performance, it's quite likely a regular expression might extract the part more efficiently than the split/strip combination, since those functions create new strings for each call. </p>

python