r/PowerShell • • Sep 17 '20

PowerShell vs Python Reference

https://blog.ironmansoftware.com/powershell-vs-python/
206 Upvotes

51 comments sorted by

View all comments

5

u/prp7 Sep 17 '20

Does powershell have something like python's list comprehension?

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(a[1:10:2])

4

u/TofuBug40 Sep 18 '20

The answers given so far using Where-Object (?) aren't really replicating what Python's notation is doing they are focusing on the VALUE of the item and not the POSITION of the item ( u/HeKis4's for loop is a valid answer) if you want to use the pipe line method what you need is

$a = ('a','b','c','d','e','f','g')
$Step = 3
$a | Where-Object -FilterScript { $a.IndexOf($_) % $Step -eq 0 }

THAT will do what the Python example above is doing step over the INDEXES of the array regardless of the values in said array

Yes its not as terse as a[0..9:3] but I would argue that pythons array split has a VERY limited use case base on the logic of iterating over an array based on a linear progression of the indexes, where as Where-Object can do that as we've shown above but can ALSO do something like

$Vowels = @('a','e','i','o','u','y')
$a | Where-Object -FilterScript { $_ -in $Vowels }

You need much more Python than a[0:10:2] to get that array result

What Where-Object lacks in the RAW terseness it MORE than makes up for in flexibility while still maintaining a respectable amount of terseness itself.

2

u/prp7 Sep 18 '20

Wow, what a story language, Mark.