Home > other >  Python changing last elements of list
Python changing last elements of list

Time:01-17

I have 2 lists

  • [A,B,C,D,E,F] - first list
  • [X,X,X,X,X,X] - second list

I would like to take last element of the first list and if there are any elements in the second list move them to the left and add the element as last.

  1. [A,B,C,D,E,F]
  2. [X,X,X,X,X,X]
  3. [A,B,C,D,E]
  4. [X,X,X,X,X,F]
  5. [A,B,C,D]
  6. [X,X,X,X,F,E]

Till there is only first element in the first array, so it would stop at:

  • [A]
  • [X,F,E,D,C,B]

I'm quite new to Python, I would really appreciate some help

CodePudding user response:

You can use for loop for this. And you can access the last elements by using -1 as index values.

CodePudding user response:

Use list pop along with index assignment

>>> l1 = ['A','B','C','D','E','F']
>>> l2 = ['X' for _ in range(len(l1))]
>>> print(l1)
['A', 'B', 'C', 'D', 'E', 'F']

>>> print(l2)
['X', 'X', 'X', 'X', 'X', 'X']

>>> for idx in range(len(l1)-1):
    p = l1.pop()
    l2[idx 1] = p
>>> print(l1)

['A']

>>> print(l2)

['X', 'F', 'E', 'D', 'C', 'B']

CodePudding user response:

try this :

l = ['A','B','C','D','E','F']
d = ['X', 'X', 'X', 'X', 'X','X']


for i in range(len(l)-1,0,-1):
    t = l.pop()
    d[-i] = t

print(l)
print(d)

['A'] ['X', 'F', 'E', 'D', 'C', 'B']

CodePudding user response:

This is the way I can do it.

first = ['A','B','C','D','E','F']
second = ['X1','X2','X3','X4','X5','X6']

print(first)
print(second)

while True:
  if len(first) > 1:
    lastElement = first[-1]
    first.remove(lastElement)
    second.append(lastElement)
    second.remove(second[0])
    print(first)
    print(second)

I added a number to the 'X' so you can see how they move. I used [-1] to save in a variable the last element of the list, and then I deleted with remove(). The same way I was adding with the method append in the second list and removing the first element with [0]. As I see in your example, you finish with [F,E,D,C,B]. In this case you can use the method .sort() to order the list. This is the output.

['A', 'B', 'C', 'D', 'E', 'F']
['X1', 'X2', 'X3', 'X4', 'X5', 'X6']
['A', 'B', 'C', 'D', 'E']
['X2', 'X3', 'X4', 'X5', 'X6', 'F']
['A', 'B', 'C', 'D']
['X3', 'X4', 'X5', 'X6', 'F', 'E']
['A', 'B', 'C']
['X4', 'X5', 'X6', 'F', 'E', 'D']
['A', 'B']
['X5', 'X6', 'F', 'E', 'D', 'C']
['A']
['X6', 'F', 'E', 'D', 'C', 'B']

CodePudding user response:

You can do the complete work using python's inbuilt list functions, like this.

list1 = ['A', 'B', 'C', 'D', 'E', 'F']
list2 = ['X'] * len(list1)

for i in range(len(list) - 1, 0, -1):
    item = list1.pop()      # Pop the last item of the first list
    list2.append(item)   # Append it to the end of the second list
    list2.remove(0)        # Shift once
    print(list1)                # For Debug
    print(list2)

CodePudding user response:

So I want to show you answers that gradually increase in complexity but also simplicity. The most simple answer (and maybe most naive one) would be this:

for i in range(len(list_1)):  # loop over every element of the list
    if len(list_1) == 1:   # when there is only one element left, break from the loop
        break
    else:
        list_2 = list_2[1:len(list_2)]   ['X'] # shift the list one to the left
        list_2[len(list_2) - 1] = list_1.pop() # insert the element at the last position

Now with a bit of observation, you can see that the last two steps are redundant. You first insert an 'X' to the last position just to replace it with the element you actually want to have there. So we can fix this by replacing it and inlining the result from the next line:

for i in range(len(list_1)):
    if len(list_1) == 1:
        break
    else:
        # shift the list and insert the last element
        list_2 = list_2[1:]   [list_1.pop()]

I have also made use of the fact that [1:len(list_2)] - meaning from index 1 to the end of the list - can just be rewritten as [1:]. You don't have to explicitly write the last element.

So far so good. Now we can further make use of the fact that if len(list_1) == 1 only really happens at the last element. So in other words, you can simply omit the last element in the for-loop and just loop once less:

for i in range(len(list_1) - 1):  # only iterate len(list_1) - 1 times
    # shift the list and insert the last element
    list_2 = list_2[1:]   [list_1.pop()]

Now a very 'pythonistic' idea is that whenever you write something in the lines of range(len(...)), you are doing something wrong. And, in fact, this expression can be simplified even more. Notice that we pop exactly len(list_1) - 1 times. With some list manipulation, this can be re-written as

list_1, temp_list = [list_1[0]], list_1[1:]  # list_1 contains now only the first element, temp_list contains all others
list_2[:len(list_1) - len(list_2):-1] = temp_list  # use negative indexing to fill list_2 up to the desired position

But it gets even better. We can combine lines 1 & 2 to the following:

list_1, list_2[:len(list_1) - len(list_2):-1] = [list_1[0]], list_1[1:]

Now this one-liner might have it's charm but comes at reduced readability. So choose your preferred style

CodePudding user response:

If I have understood, this can makes the Job:

L1 = ["a","b","c","d","e"]
L2 = ["X","X","X","X","X"]

TMP = L1[:]

for i, elmt in enumerate(TMP):
    L2[len(TMP)-i-1] = TMP[i]
    L1.pop(0)


print(L1)
print(L2)

Output :

[]
['e', 'd', 'c', 'b', 'a']
  •  Tags:  
  • Related