Python Looping

Still trying to nail down python with some basic examples I have been working through.

I am trying to control list structure within a nested for loop in python.
I want to pick the first (3) characters of my lists and output the list in the same format as the input list structure.

How do I achieve this?

Thanks in advance!

You can do this…

x = IN[0]
a =

For i in x:
… b =
…for j in i:
… … b.append(j[0:3])
…a.append(b)

OUT = a

Basically we have just added another array ‘b’ to store the inner array values and then we add this array to the outer array ‘a’ so you match the same structure as your input.

There are neater more pyrhonic ways to write this, but I think this is clearer for a beginner.

EDIT: apologies for the formatting… I’m on my mobile. :slightly_smiling_face:

2 Likes

Since I am curious, what is the more pythonic way to write this?

Thanks again for your help, that did the trick.

At this level, a nested for loop is probably the best way as it is easy to understand what is going on. If you want to go like a higher level of python, you could do lambda function in a map function. Like below:

f = lambda i : [j[0:3] for j in i]
OUT = map(f, IN[0])

Which could then be further boiled down to a single line:

OUT = map(lambda i : [j[0:3] for j in i], IN[0])

But for most purposes, the nested for loops would be just fine.

2 Likes

Or you could use a list comprehension instead of a lambda function, it’s similar but as @kennyb6 says both are not as immediately understandable as loops

OUT = [[j[:3] for j in i] for i in IN[0]]

2 Likes

You literally beat me by a minute @Thomas_Corrie!

image

Here’s Daniel’s original in an easier to read format (not being on a phone and all!)
:slight_smile:

x = IN[0]
a = []

for i in x:
    b = [] 
    for j in i:
        b.append(j[0:3])
    a.append(b)

OUT = a

Cheers,

Mark

3 Likes

Ha, yup… I would have suggested the same as @Thomas_Corrie and @Mark.Ackerley as lambda functions are more complex and scary than some list comprehension.

2 Likes

Appreciate it gentleman, I assume that the lambda functions “run” faster than the looping setup?

I’m not sure… I think that or they are probably quite comparable and maybe list comprehension might be a little faster, but probably not that noticeable with the relatively small lists we work with (maybe someone else might know). I personally prefer List comprehension just because it’s a little more readable.

1 Like

Hey,

If you do a google, you’ll find a lot of discussion about when to use a lamda, the most compelling for me, is that you can put a ‘one off’ function inside another function, which makes the code readable… Otherwise to find that function you have to scroll miles back up to find what it’s doing.

I’ll be interested to read Kenny’s view :slight_smile:

Mark