0

I have two set lists :

   a = [(1,2),(3,4),(5,6),(7,8)]
   b = [(1,5),(7,7),(2,9),(0,3)]

I want to remove first and last elements of each list. This is what I did :

for idx, f in enumerate(a):
    print(f[idx].pop(0))
    print(f[idx].pop())
for idx, g in enumerate(b):
    print(g[idx].pop(0))
    print(g[idx].pop())

Getting below error:

AttributeError: 'tuple' object has no attribute 'pop'

Expected outcome :

   a = [(3,4),(5,6)]
   b = [(7,7),(2,9)]
xixi
  • 59
  • 8

3 Answers3

5

You are trying to remove first item from tuple. But, you are expecting to remove the tuple instead. You don't need index here, just remove the first and last tuple from the list.

a.pop(0)
a.pop()

b.pop(0)
b.pop()

Or even better, do slicing.

a = a[1:-1]
b = b[1:-1]
MD. Khairul Basar
  • 4,976
  • 14
  • 41
  • 59
4

You really want to be slicing here:

>>> a = [(1,2),(3,4),(5,6),(7,8)]
>>> b = [(1,5),(7,7),(2,9),(0,3)]
>>> a[1:-1]
[(3, 4), (5, 6)]
>>> b[1:-1]
[(7, 7), (2, 9)]

If you need to pop items from both ends regularly, consider using a collections.deque instead:

>>> from collections import deque
>>> a = [(1,2),(3,4),(5,6),(7,8)]
>>> b = [(1,5),(7,7),(2,9),(0,3)]
>>> a, b = deque(a), deque(b)
>>> a.popleft()
(1, 2)
>>> a.pop()
(7, 8)
>>> a
deque([(3, 4), (5, 6)])
>>> b.popleft()
(1, 5)
>>> b.pop()
(0, 3)
>>> b
deque([(7, 7), (2, 9)])

list.pop(0) is an O(N) operation, whereas collections.deque.popleft() is an O(1) operation.

It even recommends this in https://wiki.python.org/moin/TimeComplexity:

Internally, a list is represented as an array; the largest costs come from growing beyond the current allocation size (because everything must move), or from inserting or deleting somewhere near the beginning (because everything after that must move). If you need to add/remove at both ends, consider using a collections.deque instead.

RoadRunner
  • 25,803
  • 6
  • 42
  • 75
2

You don't need to "iterate" on a list to remove the first and last element. You can use slicing, pop(), remove(), depending on the specific use case.

The following is with slicing. If a is a list, a[1:-1] returns a list where the first and last element have been removed.

Python 2.7.17 (v2.7.17:c2f86d86e6, Oct 19 2019, 21:01:17) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [(1,2),(3,4),(5,6),(7,8)]
>>> b = [(1,5),(7,7),(2,9),(0,3)]
>>> a = a[1:-1]
>>> b = b[1:-1]
>>> a
[(3, 4), (5, 6)]
>>> b
[(7, 7), (2, 9)]
>>>
damix911
  • 4,165
  • 1
  • 29
  • 44