Search code examples
pythonloopsnested-loops

Creating a for loop to delete elements in a nested list


I have a nested loop in my program, which goes like this:

x = [[a, 1, 2, 3, 4, 5], [b, 6, 7, 8, 9, 10], [c, 11, 12, 13, 14, 15]]

I've tried to create a for loop to delete the first element (a, b, c) from each nested list in the entire x list. It goes like this:

for i in x:
   del x[i][[0]

This does not work for me. I assumed that if I had 'x[i][0]' the i value would make the for loop go through every element in the entire x list, and the [0] value would allow python to delete the 0 element in the lists.


Solution

  • As fas as I understand the result that you are looking for is this: [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]

    If you run the following code:

    for i in x:
        print(i)
    

    you will get each element of x on a new line, [a, 1, 2, 3, 4, 5] first, [b, 6, 7, 8, 9, 10] second and so on. That is because when you iterate like this for i in x, i takes the values of the x (list), not its indices.

    You have two ways to eliminate the first items of every list.

    1. loop through every list and eliminate its first element. So for every list-element i in x you remove i[0]

      for i in x:
          del i[0]
      
    2. iterate through the indices of the list using range(len(x)). range(len(x)) is a list of values from 0 to len(x)-1, so i will now correspond to the indices of all elements in x.

      for i in range(len(x)):
          del x[i][0]
      

    That will get you the result you are looking for.