A Java programmer studied Python. (About type)

I'm a Java programmer who started studying Python with great momentum because I've run out of posts in Java. Click here for the previous study article on if, for, while statements.

I posted it last time with an idea, but the largest number of likes ever! I received. (Moon and soft-shelled turtle compared to the trend ...) I realized that Python is really popular.

How nice! The tension goes up by receiving It all started with garbage, but let's study Python seriously! Then write a Python reference book! I think these days.

But, "Is it for beginners, is it good for data analysis, or is it good for Web development, image analysis is hard to throw away ..." For the time being, I will study the basics of the basics while referring to various introductory sites.

Reference site

-Introduction to Python --PythonWeb -Introduction to Python (tohoho) -Python 3.6.5 documentation

Operation check environment

Mold

If you've studied PHP properly, you won't have a hard time, but in the old-fashioned Java brain, there is no type declaration. "I don't know the type at a glance .. Ugh ..." So this time I studied about molds. (Why

In Python, it seems that there are roughly 6 types (types?).

  1. Numerical value
  2. String
  3. List
  4. Set
  5. Tuple
  6. Dictionary

There are about two things that I'm not familiar with. What are tuples and dictionaries? I haven't even heard of tuples ... The dictionary is a dictionary when translated literally, but what is a dictionary type ...

For the time being, I will study while comparing with Java in order from the top.

Numerical value

There are three numeric types in Python:

  1. Integer (int)
  2. Long integer
  3. Floating point number

I've seen all of them in Java, so I'm relieved.

int In Java

IntDemo.java


int num1 = 1234; //Decimal number
int num2 = 0b10011010010; //Binary number
int num3 = 02322; //8 base
int num4 = 0x4D2; //Hexadecimal

In Python

IntDemo.py


num1 = 1234 #Decimal number
num2 = 0b10011010010 #Binary number
num3 = 0o2322 #8 base
num4 = 0x4D2 #Hexadecimal

If you try to output Java and Python in order from the top,

1234
1234
1234
1234

There was only a small difference between the octal numbers being "0" or "0o". It's going well so far.

long Next is long. In Java

LongDemo.java


long l = 9223372036854775807L;

Write Python in the same way.

LongDemo.py


l = 9223372036854775807L

Hmm? Is there an error?

SyntaxError: invalid syntax

why! Don't you just add L at the end! If you read the reference site carefully,

In Python 3, integers (ints) and long integers (longs) have been merged and treated as all integers (ints), and L and l have been deprecated.

\(^o^)/ The one above was how to write Python 2. It seems that Python 3 does not have a long. Read the reference site carefully! !! !! !! (sorry

And what's still important ...

Long integers have no limit on the number of digits as long as the memory allows, and there is no calculation error in operations between long integers.

So, it seems that any number of digits is OK as long as the memory allows.

LongDemo2.py


num = 1234567890123456789012345678901234567890123456789012345678901234567890
print(num)

Was output properly.

You don't have to be frightened by the digits ... Python is awesome ...

float

In Java, double has more valid digits, so we don't use float. It will look like the one below.

FloatDemo.java


float f = 1.2345f;

With Python

FloatDemo.py


f = 1.2345

Try to output.

1.2345

It was normal. The maximum number of digits depends on the system. There seems to be no problem with the recognition that Java double = Python float.

String

Next is a character string.

StrDemo.java


String str1 = "String";
//Same as above
String str2 = new String("String");

In the case of Python as well, the details of the movement have not been investigated, but it is written as follows.

StrDemo.py


str1 = "String"
str2 = 'String'

The enclosing character seems to be either single quotes or double quotes. Looking at Qiita and GitHub, I got the impression that many people are using single quotes. (The Java brain just wants to use double quotes ...)

By the way, you can use the plus sign to concatenate strings.

StrDemo2.py


str3 = "String" + "Linking!"

list

As you can imagine from the name, is it like an array in other programming languages? From the expectation, first try writing an array in Java.

ListDemo.java


int foo[] = [1, 2, 3, 4, 5];

If you turn this into Python

ListDemo.py


foo = [1, 2, 3, 4, 5]

Of course, there are functions such as adding, inserting, changing, and deleting elements. I will omit the movement, but I tried to summarize it.

function How to use
add to foo.append(6) #Add 6 to the end
Insert foo.insert(5, 6) #Insert 6 after the 5th in the list
Change foo[5] = 6 #Change 5th in list to 6

There were four types of deletions as far as I could find out.

Delete function How to use
Delete all elements foo.clear()
Delete the element at the specified position foo.pop(1)
Delete the same element as the specified value foo.remove("A")
Delete by specifying the position and range del foo[:3] #Remove the previous 3 elements

~~ I skipped the investigation because it was annoying, but ~~ del seems to have the syntax ** "del statement" ** instead of the method. Just remember the "syntax to delete variables and objects" and let's move on.

dictionary

It's a dictionary when translated literally, but what is a dictionary type ... On the corresponding page of the tohoho reference site, it is written as follows.

{...} holds a list of key / value pairs called a dictionary.

Is it something like Map in Java? ?? For the Python sample code, I borrowed the reference site of tohoho as it is.

DictDemo.py


d = {'Yamada': 30, 'Suzuki': 40, 'Tanaka': 80}

The order is reversed, but if you change this to Java

MapDemo.java


Map<String, Integer> d = new HashMap<String, Integer>();
d.put("Yamada", 30);
d.put("Suzuki", 40);
d.put("Tanaka", 80);

Java cannot set a value in any way without using the put () method. Python is much simpler to write than Java. ~~ Java really incompetent ~~ Remember Python dictionary type = Java Map. Also, it seems that there are more people who call it dictionary type rather than dictionary.

Tuple

I haven't even heard of it anymore. First, search Google with "tuple"! There was a "tuple" page in Wikipedia.

Tuple or tuple (English: tuple) is a general concept that collectively refers to a set consisting of multiple components. In mathematics and computer science, it is usually used to represent an ordered sequence of objects. Individually, a set of n pieces is written in English as "n-tuple", and when translated into Japanese, it is usually written as "n sets". The concept of tuple itself is sometimes called a set. In addition to meaning tuples in mathematics, n-tuple is also used to express multiples as an extension of double, triple, etc.

_〆 (-∧- ;) Hmm ... Wakaranai ... If you're an idiot who can't do math, you feel like you're being told, "Don't study Python!" (I will study

I'm sorry. This is the main subject.

This time, I have extracted from Python Web.

The tuple type is one of the sequence types as well as the character string and list types. It is composed of multiple elements, and the elements are arranged in order. In particular, there are many things in common with the list type, but tuples cannot change the elements of an object once created. Also, tuples do not have methods

Expressed in Java, is it an array (list) version of final variables? ??

When I actually write it, it looks like the one below.

TapleDemo.py


tuple = (2005, 2006, 2007, 2008)

Apparently it can't be changed, so it seems to run a little faster than the list. Use tuples if you don't plan to change the value. Other than that, it's like using a list.

By the way, if you want to define a tuple that has only one value,

TapleDemo2.py


tuple = (2005, )

It seems that you need to write a comma at the end.

bonus

I'm writing about what I thought about Python, "Hey ~ _〆 (・ ∀ ・ *)". I was in trouble with the title, so for the time being, "bonus".

Constants in Python

Python doesn't have the concept of constants. Therefore, it seems customary to use a variable name consisting of uppercase letters and underscores as a constant. I wrote it in PEP8. (Google Translate really excellent

value = 1 #Variable variable
VALUE = 1 #Treat as a constant
VALUE_MAX = 10 #Treat as a constant

String type

For Python 3 series, the character string is unicode. By the way, it seems that there are two types of 2 system, unicode and str.

Variable names starting with numbers cannot be used

As the title says. 123 is no good, hensu123 is OK.

What you told me in the comments

If there is a comma, it will be a tuple without parentheses

value = 1, 2, 3
print(value)
print(1, 2, 3)
print((1, 2, 3))

The execution result is

(1, 2, 3)
1 2 3
(1, 2, 3)

It became a tuple. The Java brain is too refreshing and uncomfortable, but it's nice because you can reduce the number of input characters.

Tuples can be used as dictionary keys

Since tuples are immutable objects, they can also be used as dictionary keys. Also, since it is not necessary to have parentheses, it seems that it can be used like specifying XY coordinates.

>>> a = {}
>>> a[(1, 2)] = 'abc'
>>> a
{(1, 2): 'abc'}
>>> a[1, 2]
'abc'

Is this area useful for statistics such as machine learning? I don't know if I forgot about math ...

Python has all values objects

In Python, all values are objects. What it means is that there are primitive types and reference types in Java, but Python seems to be like reference types in Java. So, Python has a method even though it is a numerical value. Amazing (small average feeling) The following is an excerpt from the comments.

>>> dir(-5)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> (-5).__abs__()
5

As you can see, dir seems to get a list of methods. abs seems to be a method to get the absolute value.

Impressions of trying

How to use lists, dictionaries (dictionary type) and tuples seems to be confusing. I thought, so I made it a table.

Delete function How to use
list []Surround with
dictionary(Dictionary type) {}Surround with
Tuple ()Surrounded by * Even if you do not surround it, it is OK if there is a comma

I made a mistake, but it seems that the syntax and available libraries are quite different between Python 2 and 3. If you are starting to study now, be sure to check the references and reference site versions.

Recommended Posts

A Java programmer studied Python. (About type)
A Java programmer studied Python. (About the decorator)
A Java programmer studied Python. (for, if, while statement)
A memorandum about correlation [Python]
A memorandum about Python mock
A note about [python] __debug__
Python: A Note About Classes 1 "Abstract"
A note about mock (Python mock library)
A little more about references ~ Using Python and Java as examples ~
A story about developing a soft type with Firestore + Python + OpenAPI + Typescript
[python] [meta] Is the type of python a type?
A story about Python pop and append
About February 02, 2020 * This is a Python article.
About python slices
About python comprehension
About reference type
Python numeric type
About Python tqdm.
About python yield
About python, class
python memo: Treat lists as a set type
I wrote a class in Python3 and Java
Why I'm a Java shop and start Python
A memo about writing merge sort in Python
About python inheritance
A note about the python version of python virtualenv
About python, range ()
Data analysis in Python: A note about line_profiler
A story about running Python on PHP on Heroku
Think about building a Python 3 environment in a Mac environment
About python decorators
A memorandum about the Python tesseract wrapper library
Python2 string type
Python # string type
About python reference
About Python decorators
A story about modifying Python and adding functions
[Python] About multi-process
A story about making 3D space recognition with Python
Write about building a Python environment for writing Qiita Qiita
How to write a list / dictionary type of Python3
Python points from the perspective of a C programmer
A story about making Hanon-like sheet music with Python
A story about trying a (Golang +) Python monorepo with Bazel
A memo about building a Django (Python) application with Docker
A reminder about the implementation of recommendations in Python
About Python for loops
Summary about Python scraping
A * algorithm (Python edition)
About function arguments (python)
Thinking about Java Generics
[Python] Take a screenshot
Create a Python module
Python callable type specification
A python lambda expression ...
A memorandum about matplotlib
[Python] Memo about functions
Summary about Python3 + OpenCV3
A memorandum about Nan.
About Python, for ~ (range)
Daemonize a Python process