1

I'm quite new to coding and i cannot seam to figure this problem out. I have a nested list

mnd = [
    [0, 0, 0, 0, 0, 1, 2],
    [3, 4, 5, 6, 7, 8, 9],
    [10, 11, 12, 13, 14, 15, 16],
    [17, 18, 19, 20, 21, 22, 23],
    [24, 25, 26, 27, 28, 29, 30],
    [31, 0, 0, 0, 0, 0, 0]
]

How do i split the original list in to smaller lists using a for loop while deliting the last two elements of the nested list. I can do it manually but can not figure it out how to do this in a for loop.

manually the code is this:

w1 = mnd[0]
w2 = mnd[1]
w3 = mnd[2]
w4 = mnd[3]
w5 = mnd[4]
n = 2
del w1[-n:]
del w2[-n:]
del w3[-n:]
del w4[-n:]
del w5[-n:]

How can i simplify this?

1
  • 1
    Do you mean like mnd = [element[:-2] for element in mnd]? Commented Sep 26, 2022 at 9:13

3 Answers 3

1
for k, m in enumerate(mnd):
    globals()[f'w{k + 1:d}'] = m[:-n]
Sign up to request clarification or add additional context in comments.

Comments

0

you can use indexing and re-assign the values

for indx, w in enumerate(mnd):
    mnd[indx] = w[:-2]

Comments

0

for indx, w in enumerate(mnd): mnd[indx] = w[:-2]

for i in range(1, len(mnd) + 1):
    exec(f"w{i}={mnd[i - 1]}")

print(w1,w2,w3,w4,w5)

Gave me the output that i needed. output: [0, 0, 0, 1, 2] [5, 6, 7, 8, 9] [12, 13, 14, 15, 16] [19, 20, 21, 22, 23] [26, 27, 28, 29, 30]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.