Python Beginner's Guide (Variables / Arrays)

Overview

I will write an article for beginners of python3 several times. Basically, it is an article compiled by subscribing to Introduction to O'Reilly Books Python3. This is a memo for my review, but I posted it because I thought it might be useful for someone. The reader is intended for beginners in Python programming.

This time, we will summarize Chapter 2 "Numeric values, character strings, variables" / Chapter 3 "Lists, tuples, dictionaries, sets".

Chapter 2: Numerical values, strings, variables

If you have learned other languages in Chapter 2, you don't need to know anything in particular. The only thing I can say is that I can declare it without worrying about the type ...

  • The behavior of numbers and character strings is basically the same as in other languages. Note that Python implements everything (boule values, integers, floats, strings, larger data structures, functions, programs) as objects </ Font color>. Unlike C, Java, C #, etc., you can declare variables without worrying about their types.
  • Built-in functions can be overridden, so there is a risk of rewriting
print(__import__('keyword').kwlist)  #List of reserved words

for funcs in dir(__builtins__):
    print(funcs)  #List of predefined built-in functions

str = "hoge"  #Predefined built-in functions can be overridden(Danger)
print(str)  # hoge
str(2016)  # TypeError

# None = "huga"  # 
  • python does not cause integer overflow
  • Escape is \ (backslash)
  • The line feed when printing with print () is \ n
  • Special ternary operator </ Font>

sample.py


foo = x if (x >= 0) else -x #Python ternary operator

sample.c


foo = if (x >= 0) ? x : -x; //c,java,Ternary operators such as js
  • Operations around strings can be slightly different (see below)

Unique operation of strings and arrays

Expression meaning
[0] Get the first (head) of an array / character string
[5] Get the 6th array / string
[0:5] Get the 1st to 5th of the array / character string (not including the 6th)
[:5] Get the 1st to 5th of the array / character string (from the beginning if the start position is omitted)
[5:] Get from the 6th to the end of the array / character string (until the end if the end position is omitted)
[:] Get all arrays / strings (from start to finish)
[-1] Get the first (last) counting from the end of the array / character string
[-5:-1] Get from the 5th to the 2nd from the end counting from the end of the array / character string ([-1]Does not include)
[::5] Get array / character string every 5 steps
[::-5] Get array / character string every 5 steps from behind
[::-1] Get array / string from reverse order

Arithmetic operators (integer division and exponentiation may be different from other languages ...)

operator meaning Example result
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiply 5*3 15
/ division 5/3 1.6
// Integer division (truncation) 5//3 1
% Surplus 5%3 2
** Exponentiation 5**3 125

Functions for manipulating arrays and strings

Expression meaning
len(var) var length
var.split(",") var (string)","Returns an array separated by
",".join(var) var (string or string array)","Returns a string concatenated with
var.replace(",", "") Replaces var (string) and returns a new string(In this example","To""Replace with)

Chapter 3: Lists, Tuples, Dictionaries, Sets

If you have learned other languages in Chapter 3, there seems to be no problem. However, there is a Python-like writing style (a writing style that makes good use of iterators). At first, you may feel strange about how to write a "for statement". Once you get used to it, it is convenient to use "in" to access the elements in the array. </ Font color>

  • Negative indexes allow you to access elements counting backwards from the end. (Notation like'arr [-1]')
  • How to get the array from the reverse order by making good use of the negative index is'arr [:: -1]'
  • You can create a list in a list and realize a multidimensional array.
two_dim_array = [["hoge", "huga"], [0, 1, 2], False]  #List in list
print(two_dim_array[1][0])  # output = 0
  • Use extend () or + = to join arrays
  • The order of the keys in the dictionary is not fixed and is not necessarily the order in which the elements were added.
  • Python lists, tuples, dictionaries, and sets can be mixed with variables of various types.
list_sample = ["hoge", 0, False]
tuple_sample = ("hoge", 0, False)
dict_sample = {0: "hoge", "huga": 0, 1: False}
set_sample = set("hoge", 0, False)
  • Use in in descriptions that access array elements such as for-in- and if-in-

How to write around the list

name How to write
list foo = ['tom', 'mike', 'nancy', 'jenny', 'jack']
Tuple foo = ('tom', 'mike', 'nancy', 'jenny', 'jack')
dictionary foo = {'tom': 20, 'mike': 21, 'nancy': 'unknown', 'jenny': 12, 'jack': 55}
set foo = set('tom', 'mike', 'nancy', 'jenny', 'jack')
  • Tuple: Non-duplicate array
  • Dictionary: Array with KEY and VALUE set (associative array)
  • Set: An array that leaves only the KEY from the dictionary?

How to write a multidimensional array

  • A class that handles arrays is provided in numpy, which is famous as a numerical calculation library. Handle multidimensional arrays using'numpy.ndarray'. However,'numpy.ndarray' has the following restrictions.
  • All elements in the array have the same type
  • Fixed array length (fixed length array)
  • The number of elements in each dimension of the array is the same

Also, if you want to use it for writing without using numpy, you can also use arr = [[]]. It may be a deprecated anti-pattern, so check it out.

List manipulation function

function meaning
append( val ) Add one element to the end of the list
extend( arr ) Add array (multiple elements) to the end of the list
insert( index, val ) Add element to specified index in list
del( index ) Delete the element of the list specified by the index
remove( val ) Remove the element with the specified value from the list
pop() Element pop
index( val ) Get index of element with specified value from list
count( val ) Get the number of elements with the specified value in the list
join( arr ) Converting a list to a string (inverse to the split function)
sort( reverse= True/False ) Sort the list (ascending if numerical),Alphabetical order for character strings)
len( arr ) Get the number of elements in the list
  • Val represents a variable and arr represents an array.

Dictionary manipulation function

function meaning
update( dict ) Combine dictionaries
del( key ) Delete the element with the specified key
clear( ) Delete all elements
  • Val is a variable, arr is an array, and dict is a dictionary.

When using update (dict), use it when adding a dictionary with multiple elements. If you want to add one {key: value}, you can add it by substituting with'='. (However, note that if the key is duplicated, it will be overwritten.) </ Font color>

dict_sample = {"red": 100, "green": 0, "blue": 200}
dict_sample2 = {"cyan": 50, "magenta": 60, "yellow": 70, "key_plate": 80}
dict_sample.update(dict_sample2)  #Combine dictionaries
# > dict_sample = {"red": 100, "green": 0, "blue": 200, "cyan": 50, "magenta": 60, "yellow": 70, "key_plate": 80}
dict_sample["black"] = 123  #If the key is not duplicated, it will be added
# > dict_sample = {"red": 100, "green": 0, "blue": 200, "cyan": 50, "magenta": 60, "yellow": 70, "key_plate": 80, "black": 123}
dict_sample["red"] = 123  #If the key is duplicated, it will be overwritten
# > dict_sample = {"red": 123, "green": 0, "blue": 200, "cyan": 50, "magenta": 60, "yellow": 70, "key_plate": 80, "black": 123}

Set manipulation function

function Calculation meaning Example
set1.union( set2 ) set1 | set2 Union {1,2,3} | {2,4,6} ⇒ {1, 2, 3, 4, 6}
set1.intersection( set2 ) set1 & set2 Product set (intersection) {1,2,3} & {2,4,6} ⇒ {2}
set1.difference( set2 ) set1 - set2 Difference set {1,2,3} - {2,4,6} ⇒ {1, 3}
set1.symmetric_difference( set2 ) set1 ^ set2 Exclusive OR (belongs to only one) {1,2,3} ^ {2,4,6} ⇒ {1, 3, 4, 6}
  • Set represents a set.

Combination with for, in

The Python for statement does not implement a combination of "initialization expression; continuation conditional expression; reinitialization expression". Therefore, do not write in C, C ++, etc. It is similar to the writing method that retrieves the values contained in all the elements of an array or dictionary, like the for-each statement provided by JavaScript, Java, etc.

list_sample = ["hoge", "huga", "hage"]
#Python for statement anti-patterns
for x in range(0, len(list_sample)):
    print(list_sample[x])  #Display the elements of the array one by one
#Python for statement pattern
for x in list_sample:
    print(x)  #Display the elements of the array one by one

As for the dictionary, it can be combined well with the for statement to retrieve the values contained in all the elements.

dict_sample = {"red": 100, "green": 0, "blue": 200}
#Python for statement pattern(Dictionary key only)
for k in dict_sample.keys():
    print(k)  #Display dictionary keys one by one
#Python for statement pattern(Dictionary value only)
for v in dict_sample.values():
    print(v)  #Display dictionary values one by one
#Python for statement pattern(Dictionary key,value both)
for k, v in dict_sample.items():
    print(k + ":" + str(v))  #Display the contents of the dictionary one by one

Combination with if, in

in is often used as a conditional expression. You can judge whether or not there is a specified element in a list, tuple, dictionary, or set. (In the case of a dictionary, judgment of the presence or absence of key)

list_sample = ["hoge", "huga", "hage"]
if "hoge" in list_sample: # True
    pass

Recommended Posts