Language: List Comprehensions in Python style

Created on 14 Dec 2019  路  4Comments  路  Source: dart-lang/language

I think that add a feature like list comprehensions in Python style would be a very interesting improvements in the Dart Language.
For example:

x = [i for i in range(10)]
print x

# This will give the output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

or for better understand the potentiality:

squares = [x**2 for x in range(10)]

print squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
feature

Most helpful comment

AFAIK, dart doesn't have an equivalent of the "range" function in the standard library, you have to write it yourself:

 Iterable<int> range(int n) sync* {
    for (int i = 0; i < n; ++i) {
      yield i;
    }
  }

Now you can write var x = [...range(10).map((n)=>n*n)];
Or simply: var x = [for (int i=0; i<10; i++) i*i]
(See also my response in #744)

All 4 comments

AFAIK, dart doesn't have an equivalent of the "range" function in the standard library, you have to write it yourself:

 Iterable<int> range(int n) sync* {
    for (int i = 0; i < n; ++i) {
      yield i;
    }
  }

Now you can write var x = [...range(10).map((n)=>n*n)];
Or simply: var x = [for (int i=0; i<10; i++) i*i]
(See also my response in #744)

@panthe See Making Dart a Better Language for UI in which Bob Nystrom describes Dart's features that are like list comprehensions.

@tatumizer - remember you can use for-in in list literals.

// define [range] as above
var x = [for (var i in range(10)) i];  // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var squares = [for (var i in range(10)) i*i];  // [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

The Dart way works well when you want to add some irregular elements:

var x = [66, for (var i in range(10)) i, -1];
// [66, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1]

@panthe - as you can see, Dart has essentially the same feature, we just don't use the term 'list comprehension'. I hope you don't mind if I close this issue.

remember you can use for-in in list literals.

I remember. I used it in the example in #744 :-)

Nice Idea!!!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

leafpetersen picture leafpetersen  路  3Comments

architkithania picture architkithania  路  5Comments

kevmoo picture kevmoo  路  3Comments

har79 picture har79  路  5Comments

jonasfj picture jonasfj  路  3Comments