Remove First and Last Item of Nested List With Python

Hi guys, I’m trying to define a function that removes nested lists’ first and last items using Python. I’m struggling to figure out what I am missing. See my code below.
Thanks for your help.

nestedList = [["a","b","c","d","e"],["f","g","h","i","j"],["k","l","m","n","o"]]


def Sortlist(list):
    listVal1 = []
    listVal2 = []
    count = 0
    for n in list:
        for nn in n:
            count = count + 1
            if count == 0:
                listVal1.append(nn)
            elif count ==len(n):
                listVal1.append(nn)
            else:
                listVal2.append(nn)
    return listVal1, listVal2
       




OUT = map(Sortlist,nestedList)

Voila

nestedList = [["a","b","c","d","e"],["f","g","h","i","j"],["k","l","m","n","o"]]


def Sortlist(list):
	return map(lambda x: x[1:-1],list)
	
OUT = Sortlist(nestedList)

3 Likes

Thanks so much. I forgot to mention that I actually want the first and last items in a list and the rest in a separate list. That’s why I had two lists in my function.

I think I understand how to do it

return map(lambda x: x[0:len(list)-1], list)

Could also do this:

def Sortlist(list):
    inside = list[1:-1]
    outside = [i for i in list if i not in inside]
    return [inside,outside]

OUT = map(Sortlist,nestedList)
4 Likes

Hi All. Thanks for the help. Learnt a few things here.
I got my first code to work, but Nick’s option is the most concise.
Thank you.

nestedList = [["a","b","c","d","e","y"],["f","g","h","i","j"],["k","l","m","n","o"]]


def sortFirstLast(list):
    listVal1 = []
    listVal2 = []
    count = -1
    for n in list:
        count = count + 1
        if count == 0:
            listVal1.append(n)
        elif count == len(list)-1:
            listVal1.append(n)
        else:
            listVal2.append(n)
    return listVal1, listVal2

Perhaps some more education - this can be accomplished with list comprehension and list slicing directly as well. No need for a definition as it’s already built in! :smiley:

nestedLists = ["HelloWorld"[n*5:n*5+5] for n in range(len("HelloWorld")/5)]
listCombos = [ [lst, lst[::len(lst)-1], lst[1:-1]] for lst in nestedLists ] #uses list comprehension, and list slicing to get the data you're after
OUT = listCombos
3 Likes

I’m curious as to the use cases for both map() and lambda functions over list comprehension and def. I’ve seen both used quite often, but on searching through stack overflow it seems opinions are quite divided on when it’s right to use either.

From what I understand, lambdas are throwaway functions and map() is effectively list comprehension in principle that takes a function and iterable. I’ve noticed you use both often so thought I’d pick your brains to see if you know the benefits of them. I’m thinking it’s mainly a memory usage thing when it comes to lamdbas, and legibility maybe?

edit: stumbled across a super answer thread, but if you have further tips/input let me know!

2 Likes

Thanks for the added info @jacob.small @GavinCrump. Will have a look.

I’ll weigh in with my two cents here. :slight_smile:

To me there are four possible reasons to use any one method over another when coding. In no particular order they are:

  1. Speed
  2. Readability
  3. Keeping to standard
  4. Scalability

When you chose one over the other is entirely situational, but the logic which applies the weight to each factor is worth considering.

Speed is pretty straight forward - everyone wants code to run faster, in call cases. Otherwise we’d just do this all manually, right? In the context of Python the timeit module is useful for exploring execution time, and is worth learning.

Readability is VERY important with code, but you need to keep in mind who your target audience is in doing so. Commenting helps a lot here, but at a point overly verbose comments become difficult for seasoned coders to work with. If the target audience is “very pythonic” in nature, then list comprehensions might be best; but if they tend to C# you might want to consider a for loop.

Keeping to a standard is also pretty straight forward, just like most of the BIM stuff we are used to. If every other coder in the company utilizes lambda, you should to. This is a bit of a cop out in that someone else (or the wisdom of the crowd) is technically making the decision for you, but it’s best to be part of the team rather than an outlier for this stuff. At scale software is a team effort after all.

Scalability entails reading the tea leaves around ‘where and how might this code be reused. If you intend to move from a Python code base to a Revit add-in at some point then you might want to move away from list comprehension early on to keep the code base similar in nature. Conversely if you know you’ll never utilize anything other than Python, the compact structure and reduced formatting restrictions of list comprehensions can make moving functions across code quite a bit easier.

5 Likes

Thanks for the input Jacob, great points! You nailed the one about leaving a legacy/system for others to build on and learn from - currently teaching my computation team Python and want to make sure I teach them the best methods. The comment RE correlation to C is also a great one, one of them I’m bringing up from visual and the other back from C (in Rhino), they did mention lambda as benefiting in similarity as well as not liking comprehension for the opposite reason.