DEV Community

Sreekar Reddy
Sreekar Reddy

Posted on • Originally published at sreekarreddy.com

πŸš‚ Arrays Explained Like You're 5

Train compartments in a row

Day 24 of 149

πŸ‘‰ Full deep-dive with code examples


The Train

Imagine a train with numbered compartments:

πŸš‚ [Car 0] [Car 1] [Car 2] [Car 3] [Car 4]
Enter fullscreen mode Exit fullscreen mode

Each car has a number (starting from 0!) and can hold one thing.

Arrays are trains for your data!


In Code

fruits = ["apple", "banana", "cherry", "date"]
Enter fullscreen mode Exit fullscreen mode
Index:    0         1          2        3
       ["apple", "banana", "cherry", "date"]
Enter fullscreen mode Exit fullscreen mode

To get banana: fruits[1] (index 1, the second item)


Why Start at 0?

Tradition from early computers! Just remember:

  • First item = index 0
  • Second item = index 1
  • Third item = index 2

What Can You Do?

Action Code Result
Get item fruits[2] "cherry"
Change item fruits[0] = "apricot" Updates first item
Add item fruits.append("elderberry") Adds to end
Count len(fruits) 5

In One Sentence

Arrays store multiple items in a numbered list, like numbered train compartments in a row.


πŸ”— Enjoying these? Follow for daily ELI5 explanations!

Making complex tech concepts simple, one day at a time.

Top comments (0)