Let's see how to count the number of elements in an array in some languages [Go, JavaScript, PHP, Python, Ruby, Swift]

Recently, I have come into contact with several languages in my work, and when I go back and forth between multiple languages, the simple syntax may get confused.

For the sake of organizing my mind, this time I will look at how to count the number of elements in an array in some languages.

All of them are shallow, so I hope that professionals in each language will take a calm look. : pray:

Appearance language

▶︎ Go

The Go language provides len () as a built-in function. Therefore, you can get the number of elements in the array in the form len (array).

Also, in Go, there are Array type and Slice type as array-like types, The Array type of Go has a fixed number of elements, and it seems that the Slice type is closer when used like an array in other languages. Therefore, Slice is also used in the following code example.

Code example

package main

import (
	"fmt"
)

func main() {

	languages := []string{"Go", "JavaScript", "PHP", "Python", "Ruby", "Swift"}
	fmt.Println(len(languages)) // -> 6

}

Go Playground: https://play.golang.org/p/r6yPBOU5uC

(Author execution version: Runtime version of Go Playfround → https://play.golang.org/p/1VcPUlPk_3)

Supplement

In addition to Array and Slice, map, String, Channel, etc. can be taken as the argument of len, and it seems that the length that matches the type is returned. (Array and map are the number of elements, String is the number of bytes, etc.)

reference

https://golang.org/pkg/builtin/#len

▶︎ JavaScript

In JavaScript, Array has a length property. Therefore, you can get the number of elements with ʻarray.length`.

Code example

var languages = ["Go", "JavaScript", "PHP", "Python", "Ruby", "Swift"];
console.log(languages.length); // -> 6

Supplement

It is the length property of Array, but it seems that it is writable, and if you shorten the length, the elements in the array also change. I knew this for the first time.

languages.length = 3;
console.log(languages); // -> ["Go", "JavaScript", "PHP"]

reference

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/length

▶︎ PHP

PHP provides a function called count (). Therefore, you can get the number of elements in the array in the form count ($ array).

Code example

$languages = array("Go", "JavaScript", "PHP", "Python", "Ruby", "Swift");
// PHP 5.After 4 it is OK to write as below
// $languages = ["Go", "JavaScript", "PHP", "Python", "Ruby", "Swift"];
echo(count($languages)); // -> 6

(Author running version: PHP 5.3.27) Old. Lol

Supplement

There is also an alias for count () called sizeof (), so it's exactly the same.

It's similar to Go in passing an array as an argument to a built-in function, but unlike Go, passing a String doesn't return the number of bytes.

reference

http://php.net/manual/ja/function.count.php

▶︎ Python

In Python, the word array is not used in the first place, and the equivalent of an array is called a list. To get the number of elements in the list, use the built-in function len ().

Code example

languages = ["Go", "JavaScript", "PHP", "Python", "Ruby", "Swift"]
print len(languages) # -> 6

(Author execution version: Python 2.7.12)

Supplement

In the reference

Arguments can be sequences (strings, bytes, tuples, lists, ranges, etc.) or collections (dictionaries, sets, frozen sets, etc.).

So, this is similar to Go, and you can see that it returns the length of each other than the list.

reference

2 system http://docs.python.jp/2/library/functions.html#len 3 series http://docs.python.jp/3/library/functions.html#len

▶︎ Ruby

In Ruby, the Array class has a length method and asize method, both of which can get the number of elements. (The size method seems to be an alias for the length method)

Also, since the Enumerable module included in the Array class has a count method, you can get the number of elements in the array by using the count method with no arguments in the Array class as well.

Code example

languages = ["Go", "JavaScript", "PHP", "Python", "Ruby", "Swift"]
p languages.length # -> 6
p languages.size # -> 6
p languages.count # -> 6

(Author execution version: ruby 2.3.0)

Supplement

I think the following article will be helpful for the difference between the length method and the count method. http://qiita.com/saino-katsutoshi/items/7d761c026563a649d046

reference

http://ruby-doc.org/core-2.3.0/Array.html#method-i-length

▶︎ Swift

In Swift, the Array structure has a count property, so you can get the number of elements from this count property.

Code example

let languages = ["Go", "JavaScript", "PHP", "Python", "Ruby", "Swift"]
print(languages.count) // -> 6

(Author execution version: Swift 3.0)

Supplement

The Array structure conforms to the Collection protocol, so the count property must be defined. It's also similar to JavaScript's length property in terms of properties, but Swift's count property is read-only, so you can't rewrite its value.

reference

https://developer.apple.com/reference/swift/array/1539982-count

Summary

First of all,

--Language where functions / properties that return the number of elements in the array class (etc.) are defined, such as ʻarray_object.count_method_or_property**, and --Language that has a function that returns the length of the object passed as an argument as a built-in function ** likecount_function (array_object)` **

There seems to be.

Furthermore, even if it is divided, "property or method" is different, and "whether the content of the value returned depends on the type passed to the argument" is different depending on the language.

It's interesting that it depends on the language whether or not the array object keeps track of the number of its elements.

Also, there are still many parts that I haven't learned deeply about each language, so I'll study little by little.

Recommended Posts

Let's see how to count the number of elements in an array in some languages [Go, JavaScript, PHP, Python, Ruby, Swift]
How to count the number of elements in Django and output to a template
How to get the number of digits in Python
How to handle JSON in Ruby, Python, JavaScript, PHP
How to count the number of occurrences of each element in the list in Python with weight
How to swap elements in an array in Python, and how to reverse an array.
How to know the internal structure of an object in Python
[Python] Let's reduce the number of elements in the result in set operations
Summary of how to write increment / decrement (Scala, Java, Rust, C, C ++, Go, PHP, Perl, Python, Ruby, JavaScript)
Set the number of elements in a NumPy one-dimensional array to a power of 2 (0 padded)
Get the size (number of elements) of UnionFind in Python
How to identify the element with the smallest number of characters in a Python list?
How to check in Python if one of the elements of a list is in another list
How to find the optimal number of clusters in k-means
Get the number of specific elements in a python list
How to quickly count the frequency of appearance of characters from a character string in Python?
How to specify an infinite number of tolerances in the numeric argument validation check of argparse
[Homology] Count the number of holes in data with Python
How to get rid of the "Tags must be an array of hashes." Error in the qiita api
Memo of the program to get the date in two digits with javascript, Ruby, Python, shell script
Count the number of Thai and Arabic characters well in Python
How to determine the existence of a selenium element in Python
How to make a string into an array or an array into a string in Python
How to check the memory size of a variable in Python
How to check the memory size of a dictionary in Python
Summary of how to write if statements (Scala, Java, Rust, C language, C ++, Go language, PHP, Perl, Python, Ruby)
How to write the correct shebang in Perl, Python and Ruby scripts
Comparing the basic grammar of Python and Go in an easy-to-understand manner
[Python] How to put any number of standard inputs in a list
[Scraping Summary] | Python Node.js PHP Ruby Go VBA | Scraping Yahoo! Top in 6 languages
Extract every n elements from an array (list) in Python and Ruby
[Python] How to use list 2 Reference of list value, number of elements, maximum value, minimum value
An example of the answer to the reference question of the study session. In python.
How to sort by specifying a column in the Python Numpy array.
I made a function to see the movement of a two-dimensional array (Python)
How to write Ruby to_s in Python
[Python] Combine all the elements in the array
[Python] Precautions when finding the maximum and minimum values in a numpy array with a small number of elements
python: Tips for displaying an array (list) with an index (how to find out what number an element of an array is)
Part 1 I wrote an example of the answer to the reference problem of how to write offline in real time in Python
How to pass the execution result of a shell command in a list in Python
Divides the character string by the specified number of characters. In Ruby and Python.
[python] How to sort by the Nth Mth element of a multidimensional array
Set an upper limit on the number of recursive function iterations in Python
Visualize the timeline of the number of issues on GitHub assigned to you in Python
How to find the coefficient of the trendline that passes through the vertices in Python
Checklist on how to avoid turning the elements of numpy's array with for
Get the last element of the array by splitting the string in Python and PHP
How to get a list of files in the same directory with python
"A book to train programming skills to fight in the world" Python code answer example --1.2 Count the number of the same characters
Output the number of CPU cores in Python
Summary of how to import files in Python 3
Summary of how to use MNIST in Python
How to get dictionary type elements of Python 2.7
Output in the form of a python array
Grouping combination in Python / Ruby / PHP / Golang (Go)
How to remove duplicate elements in Python3 list
From the initial state of CentOS8 to running php python perl ruby with nginx
An easy way to pad the number with zeros depending on the number of digits [Python]
Pass an array from PHP to PYTHON and do numpy processing to get the result
How to retrieve the nth largest value in Python