Ted Idzikowski Ted Idzikowski - 6 months ago 27
Python Question

Removing third element and second from each list and finding lists which have last elements within specific range in a 2D list

I have two questions.

First Question:

I would like to know how I can remove each second element and third element from a 2-D list questions, so that if the variable questions initially is as follows:

>>> questions
>>> [['Johny', 'Baby', 'Shaw', '1984'], ['Andrew', 'fJKC', 'cbv bv', '1975'], ['Harry', 'Jack', 'Son', '1993']]

The resulted outcome becomes:

>>> questions
>>> [['Johny', '1984'], ['Andrew', '1975'], ['Harry', '1993']]

Second Question:

How can I find a way knowing two values: (minimum value, maximum value), to print whatever of the three lists in the list questions which the last element is in the range (minimum value, max value).

Expected outcome:

If, following obviously the previous outcome, for example, the minimum value is
and the maximum value is
. It prints the following:

>>> ['Johny', '1984'], ['Harry', '1993']

Here's my attempt:

beginning = int(input('Enter beginning year: '))
ending = int(input('Enter ending year: '))
position = []
for anyitem in range((len(questions)-1)):
position1 = int(questions[anyitem][2][-4:])
if beginning < position1 < ending:

Please, do not use
or any functions that need to be imported. Also, please make the solution general, so it can be applied to a 2D list with not only 3 elements (as in my case) but many elements (for everyone).


Both can be easily accomplished with list comprehensions.

Removing certain elements:

>>> nquestions = [[i ,j] for i, *_, j in questions]
>>> nquestions
[['Johny', '1984'], ['Andrew', '1975'], ['Harry', '1993']]

Here we unpack from each sub-list tossing away the middle elements with *_ while keeping the first and last in order to create the new list from them.

For filtering, it is best to create a custom range and use another list comprehension to filter out the values that are in that range:

>>> r = range(1980, 2000)
>>> [i for i in nquestions if int(i[1]) in r]
[['Johny', '1984'], ['Harry', '1993']]

int(i[1]) required due to the fact that the values are strings. Apart from being very intuitive, membership tests for range objects are quite efficient.