Home > front end >  How to print all values except for the first element of the first list in a 2d Array in Python
How to print all values except for the first element of the first list in a 2d Array in Python

Time:04-24

So, for example, if we have the 2D Array:

list_2D = [[1, 2, 3], [4, 5, 6]]

I want it to be able to print out:

[[2, 3], [4, 5, 6]]

So far, I have tried splicing the list, but I can't figure out a way to isolate just the first element of the first list within the 2D Array. I feel like the answer lies in list comprehension, but, again, I'm not sure how I would isolate the first element of the first list. It would be preferrable, if it's possible, if this could fit in just 1 print statement. Thank you!

CodePudding user response:

Just for fun a hack that in one line removes the number, prints, and puts the number back in:

list_2D[0][print(list_2D):0] = list_2D[0].pop(0),

Try it online!

CodePudding user response:

You can pop the value and then print:

list_2D = [[1, 2, 3], [4, 5, 6]]
list_2D[0].pop(0)
print(list_2D)

If you don't want to change the original list, consider copying it and do this on the copy.

CodePudding user response:

Try:

print([list_2D[0][1:], *list_2D[1:]])

Prints:

[[2, 3], [4, 5, 6]]
  • Related