# About changing list inside a list

**URL:** <https://forums.kodeco.com/t/about-changing-list-inside-a-list/182995>\
**Category:** Dart Apprentice: Fundamentals\
**Created:** [January 21, 2023, 2:18pm UTC](https://forums.kodeco.com/t/about-changing-list-inside-a-list/182995 "2023-01-21T14:18:39Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ellery](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/ellery/32/110937_2.png) [@ellery](https://forums.kodeco.com/u/ellery)\
**Post date:** [January 21, 2023, 2:18pm UTC](https://forums.kodeco.com/t/about-changing-list-inside-a-list/182995/1 "2023-01-21T14:18:39Z")

</div>

I just read chapter 12, the part about shallow copy and deep copy. I just want to write some code to illustrate this. My code as follows:

```dart
  var a = [
    [1, 2],
    2,
    3
  ];
  var b = List.of(a);
  b.remove(3);
  b[0].add(3);
  print(b);
  print(a);

```

I have error on the line `b[0].add(3)`. Could anyone tell me why this error occur and the fix to it?

---

<div class="post-metadata">

**Author:** ![suragch](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/suragch/32/109020_2.png) [@suragch](https://forums.kodeco.com/u/suragch)\
**Post date:** [January 25, 2023, 9:31am UTC](https://forums.kodeco.com/t/about-changing-list-inside-a-list/182995/2 "2023-01-25T09:31:35Z")

</div>

The Dart analyzer gives the following error message for that line:

```nohighlight
The method 'add' isn't defined for the type 'Object'.

```

You mixed two different types in your `a`-list. The type of the first element is `List<int>` and the types of the next two elements are `int`. Since your `a` list contains mixed types, Dart infers the type contained in your `a`-list to be `Object`, which is the nearest common supertype of `int` and `List`.

Your `b`-list is a copy of your `a`-list, so it is also the same type, that is, `List<Object>`.

When you call `b[0]`, you are accessing the first element of the `b`-list. The only thing Dart knows about this first element is that it is of type `Object`. You can’t `add` anything to an Object, so Dart gives you an error. _You_ know that it is actually a list, but Dart doesn’t know that.

You can fix the error by telling Dart the type. Do this by downcasting `Object` to `List<int>` using the `as` keyword, like so:

```auto
(b[0] as List<int>).add(3); 

```

The error disappears.

---

<div class="post-metadata">

**Author:** ![ellery](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/ellery/32/110937_2.png) [@ellery](https://forums.kodeco.com/u/ellery)\
**Post date:** [January 26, 2023, 8:15am UTC](https://forums.kodeco.com/t/about-changing-list-inside-a-list/182995/3 "2023-01-26T08:15:45Z")

</div>

Thank you. @suragch Now I can using to illustrate what is shallow copy. Thank you for pointing out my mistake. I am really not aware of this. May be I come from experience in duck typing language like Python.
