Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python list comprehensions invalid syntax while if statement

I've got list like this z = ['aaaaaa','bbbbbbbbbb','cccccccc'] i would like to cut off first 6 chars from all elements and if element is empty not to put in another list. So I made this code:

[x[6:] if x[6:] is not '' else pass for x in z]

I've tried with

pass continue

and still syntax error. Maybe someone could help me with it? thanks

like image 553
Krystian Avatar asked May 16 '26 06:05

Krystian


2 Answers

Whenever you need to filter items from a list, the condition has to be at the end. So you need to filter the empty items, like this

[x[6:] for x in z if x[6:] != ""]
# ['bbbb', 'cc']

Since, an empty string is falsy, we can write the same condition succinctly as follows

[x[6:] for x in z if x[6:]]

As an alternative, as tobias_k suggested, you can check the length of the string like this

[x[6:] for x in z if len(x) > 6]
like image 86
thefourtheye Avatar answered May 18 '26 19:05

thefourtheye


If you are learning to do with lambda(not an official link), you should try with map and filter like this:

filter(None, map(lambda y: y[6:], x))

Here, the map(lambda y: y[6:], x) will keep only strings from 7th character and replace other smaller strings with Boolean 'False'. To remove all these 'False' values from the new list, we will use filter function.

You can take this only for learning purposes as this is downright ugly when Python's PEP8 is considered. List comprehension is the way to go like mentioned above.

[y[6:] for y in x if y[6:]]

Or the traditional for loop as

output = []
for y in x:
    if isinstance(y, str) and y[6:]:
        output.append(y[6:])

Please note that even though the traditional way looks bigger, it can add more values(like here, taking only the strings from the list if the list has other data types such as lists, tuples, dictionaries, etc)

So I would suggest either to stick with list comprehensions for simple controlled lists or the traditional way for controlled output

like image 25
thiruvenkadam Avatar answered May 18 '26 20:05

thiruvenkadam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!