Skip to content
mengfung.com
writing

RUBY ARRAYS & PYTHON LISTS

 ·  1 min read

I remember when I had to do linked list in c++ without stdlib. Those days are gone!

Python:

>>> a = [10,20,30,40,20,40,50]
>>> a
[10, 20, 30, 40, 20, 40, 50]
>>> len(a)
7
>>> a.insert(3,"x")
>>> a
[10, 20, 30, 'x', 40, 20, 40, 50]
>>> a.append("y")
>>> a
[10, 20, 30, 'x', 40, 20, 40, 50, 'y']
>>> a.index("x")
3
>>> a.remove(20)
>>> a
[10, 30, 'x', 40, 20, 40, 50, 'y']
>>> a.pop()
'y'
>>> a
[10, 30, 'x', 40, 20, 40, 50]
>>> a.count(40)
2
>>> a.sort()
>>> a
[10, 20, 30, 40, 40, 50, 'x']
>>> a.reverse()
>>> a
['x', 50, 40, 40, 30, 20, 10]

Ruby:

>> a = [10,20,30,40,20,40,50]
=> [10, 20, 30, 40, 20, 40, 50]
>> a.size
=> 7
>> a[3,0] = "x"
=> "x"
>> a
=> [10, 20, 30, "x", 40, 20, 40, 50]
>> a << "y"
=> [10, 20, 30, "x", 40, 20, 40, 50, "y"]
>> # when using ruby's delete it will delete all instances of
>> a.delete_at(a.index(20))
=> 20
>> a
=> [10, 30, "x", 40, 20, 40, 50, "y"]
>> a.pop
=> "y"
>> a
=> [10, 30, "x", 40, 20, 40, 50]
>> # ruby doesn't have anything similar to a.count(40)
>> # ruby can't sort when there is int and str.  
>> # you could turn everything into a str using .to_s and then sort.
>> a.delete_at(2)
=> "x"
>> a.sort
=> [10, 20, 30, 40, 40, 50]
>> a.reverse
=> [50, 40, 20, 40, 30, 10]
>> # ruby has a lot more methods on array check the api