Basic grammar of Python3 series (list, tuple)

Overview

Refer to O'Reilly Japan's "Introduction to Python 3" and the following Python Japanese translation document. Study the basic grammar of Python3 system. I hope it will be helpful for those who want to study Python in the same way.

Python 3.6.1 documentation https://docs.python.jp/3/index.html

Sequence type

The sequence type is a data structure for handling 0 or more elements. The basic sequence type corresponds to list, tuple, range, etc.

List type (list)

Lists are suitable for mutable sequences where the order and content may change. Also, the same value may appear more than once in the list. (If you don't care about the order if you can manage unique values, you may want to use a set)

Created by [] or list ()

>>> #Creating an empty array[]
>>> empty_list1 = []
>>> empty_list1
[]

>>> #List creation[]
>>> str_list1 = ['A','B','C']
>>> str_list1
['A', 'B', 'C']

>>> #Creation of empty array list()
>>> empty_list2 = list()
>>> empty_list2
[]

>>> #List creation list()
>>> str_list2 = list(['A','B','C'])
>>> str_list2
['A', 'B', 'C']

Conversion from other data types to list types

>>> #Convert strings to lists
>>> list('ABC')
['A', 'B', 'C']

>>> #Convert tuples to lists
>>> tuple_sample = ('A','B','C')
>>> list(tuple_sample)
['A', 'B', 'C']

>>> #Convert the split result of split to a list
>>> today = '2017/07/01'
>>> today.split('/')
['2017', '07', '01']

>>> #Convert split result to list (if empty string element is included)
>>> target = 'A//B/C/DE///F'
>>> target.split('/')
['A', '', 'B', 'C', 'DE', '', '', 'F']
>>> target.split('//')
['A', 'B/C/DE', '/F']

Extraction of elements with [offset] specified

>>> target = ['A','B','C']

>>> #Specify a positive index
>>> target[0]
'A'
>>> target[1]
'B'
>>> target[2]
'C'

>>> #Specify a negative index (count in reverse order from the end)
>>> target[-1]
'C'
>>> target[-2]
'B'
>>> target[-3]
'A'

>>> #Error if offset out of range is specified
>>> target[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

List of lists

List types can store elements of different types (including other list types).

>>> str_upper = ['A','B','C']
>>> str_lower = ['a','b','c']
>>> str_number = [1 ,'2','3',4]
>>> all_str = [str_upper, str_lower, str_number]

>>> #List of lists
>>> all_str
[['A', 'B', 'C'], ['a', 'b', 'c'], [1, '2', '3', 4]]

>>> #The first element from the list in the list
>>> all_str[0]
['A', 'B', 'C']

>>> #The second element from the list in the list
>>> all_str[1]
['a', 'b', 'c']

>>> #Third element from the list in the list
>>> all_str[2]
[1, '2', '3', 4]

>>> #If you specify two indexes, only the elements of the built-in list will be returned.
>>> all_str[1][0]
'a'

Rewriting the element with [offset] specified

Since the list is mutable, you can rewrite the value by specifying the offset.

>>> target = ['A','B','C']
>>> target
['A', 'B', 'C']

>>> target[1] = 'V'
>>> target
['A', 'V', 'C']

>>> #Append to add elements to the list()Do by
>>> target[3] = 'D'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range

Extraction by slice with [offset] range specified

>>> target = ['A','B','C']
>>> target
['A', 'B', 'C']

>>> #From the beginning
>>> target[0:]
['A', 'B', 'C']

>>> #2 letters from the beginning
>>> target[0:2]
['A', 'B']

>>> #Reverse the elements of the list
>>> target[::-1]
['C', 'B', 'A']

Append element to the end with append ()

>>> target = ['A','B','C']
>>> target.append('D')
>>> target
['A', 'B', 'C', 'D']

Add element with insert ()

Since the append () function adds an element to the end, use this if you want to add an element by specifying an offset and an additional position. Also, if an offset beyond the end is specified, it will be added to the end of the list. (No exceptions can be thrown for incorrect offsets)

>>> target = ['A','B','C']

>>> #Added to the 3rd character
>>> target.insert(2,'Q')
>>> target
['A', 'B', 'Q', 'C']

>>> #If you specify an offset that exceeds the end
>>> target.insert(10,'Z')
>>> target
['A', 'B', 'Q', 'C', 'Z']

>>> #When counting from the end
>>> target.insert(-2,'V')
>>> target
['A', 'B', 'Q', 'V', 'C', 'Z']

Deleting elements with del

Since del is a Python statement, not a list method, we don't write del ().

>>> target = ['A','B','C','D','E']

>>> #Delete the third character
>>> del target[2]
>>> target
['A', 'B', 'D', 'E']

>>> #Delete the end
>>> del target[-1]
>>> target
['A', 'B', 'D']

Remove element with remove ()

If you want to specify an element and delete it instead of specifying an offset, use this instead of del.

>>> target = ['A','B','C','D','E']
>>> target.remove('B')
>>> target
['A', 'C', 'D', 'E']

Extracting and deleting elements with pop ()

You can use pop () to retrieve an element from the list and remove it from the list at the same time. If no argument is specified, -1 (end) is specified as the offset.

>>> target = ['A','B','C','D','E','F','G']
>>> #Pop the third character
>>> target.pop(2)
'C'
>>> target
['A', 'B', 'D', 'E', 'F', 'G']

>>> #Pop trailing character
>>> target.pop()
'G'
>>> target
['A', 'B', 'D', 'E', 'F']

>>> #Pop the first character
>>> target.pop(0)
'A'
>>> target
['B', 'D', 'E', 'F']

Combine lists using extend () or + =

>>> # extend()Combine list by
>>> target1 = ['A','B','C']
>>> target2 = ['D','E']
>>> target1.extend(target2)
>>> target1
['A', 'B', 'C', 'D', 'E']

>>> # +=Combine list by
>>> target1 = ['A','B','C']
>>> target2 = ['D','E']
>>> target1 += target2
>>> target1
['A', 'B', 'C', 'D', 'E']

Check element offset by index ()

>>> target = ['A','B','C','D','E','F','G']
>>> target.index('D')
3

Presence / absence judgment of value using in ()

>>> target = ['A','B','C','D','E','F','G']
>>> 'A' in target
True
>>> 'Z' in target
False

Counting the number of values using count ()

>>> target = ['A','A','A','B','B','C']
>>> target.count('A')
3
>>> target.count('B')
2
>>> target.count('C')
1

Convert to string with join ()

join () is a string method, not a list method.

>>> target = ['A','B','C','D','E','F','G']
>>> ','.join(target)
'A,B,C,D,E,F,G'

Get the number of elements with len ()

>>> target = ['A','B','C','D','E','F','G']
>>> len(target)
7

Sorting elements by sort () (Supplementary when using general-purpose functions)

>>> #General function sorted()Ascending sort by
>>> target = ['C','E','A','D','B','F']
>>> sorted_target = sorted(target)
>>> sorted_target
['A', 'B', 'C', 'D', 'E', 'F']

>>> #General function sorted()Descending sort by
>>> target = ['C','E','A','D','B','F']
>>> sorted_target = sorted(target, reverse=True)
>>> sorted_target
['F', 'E', 'D', 'C', 'B', 'A']

>>> #List function sort()Ascending sort by
>>> target = ['C','E','A','D','B','F']
>>> target.sort()
>>> target
['A', 'B', 'C', 'D', 'E', 'F']

>>> #List function sort()Descending sort by
>>> target = ['C','E','A','D','B','F']
>>> target.sort(reverse=True)
>>> target
['F', 'E', 'D', 'C', 'B', 'A']

Copying the list with copy () (Supplement to other copying methods)

>>> target = ['A','B','C']

>>> #List copy()Copy by function
>>> target1 = target.copy()
>>> target1
['A', 'B', 'C']

>>> # list()Copy by conversion function
>>> target2 = list(target)
>>> target2
['A', 'B', 'C']

>>> #Copy by list slice
>>> target3 = target[:]
>>> target3
['A', 'B', 'C']

Tuple type (tuple)

Unlike lists, tuples are immutable sequences, so you cannot add, remove, or change elements after defining a tuple. Also, since there are no functions such as append () and insert (), there are fewer functions than lists.

As a way of using properly, use tuples when dealing with constant lists. Other points to consider are as follows.

--Tuples consume less space. --There is no risk of rewriting tuple elements. --Tuples can be used as dictionary keys. --Named tuples can be used as a simple alternative to objects. --Function arguments are passed as tuples.

Creating tuples

>>> #Creating an empty tuple
>>> empty_tuple = ()
>>> empty_tuple
()

>>> #Tuple with one element (with a comma at the end)
>>> target1 = 'A',
>>> target1
('A',)

>>> #Tuples with multiple elements (comma at the end can be omitted)
>>> target2 = 'A','B','C'
>>> target2
('A', 'B', 'C')

>>> #It is easier to understand if this is a tuple because it does not cause an error even if you put parentheses
>>> target3 = ('A','B','C')
>>> target3
('A', 'B', 'C')

Conversion to tuples by tuple ()

>>> str_list = ['A','B','C']
>>> tuple(str_list)
('A', 'B', 'C')

Other

Sequence unpack

>>> #List unpacked assignment
>>> str_list = ['A','B','C']
>>> s1, s2, s3 = str_list
>>> s1
'A'
>>> s2
'B'
>>> s3
'C'

>>> #Tuple unpacked substitution
>>> str_tuple = ('A','B','C')
>>> s1, s2, s3 = str_tuple
>>> s1
'A'
>>> s2
'B'
>>> s3
'C'

Recommended Posts

Basic grammar of Python3 series (list, tuple)
Basic operation list of Python3 list, tuple, dictionary, set
Basic grammar of Python3 system (dictionary)
Python3 basic grammar
Basic grammar of Python3 system (character string)
Basic grammar of Python3 system (included notation)
List of python modules
Python basic grammar / algorithm
Python basic grammar (miscellaneous)
Python basic grammar note (4)
Python basic grammar note (3)
Basic knowledge of Python
Python basic grammar memo
Basic operation of Python Pandas Series and Dataframe (1)
Summary of Python3 list operations
Summary of Python sort (list, dictionary type, Series, DataFrame)
Python installation and basic grammar
Python Basic Grammar Memo (Part 1)
Python Basic Course (5 List Tuples)
Python basic grammar (miscellaneous) Memo (2)
Basic Python grammar for beginners
[Python] Copy of multidimensional list
Basic usage of Python f-string
I learned Python basic grammar
Python basic grammar (miscellaneous) Memo (4)
Python (Python 3.7.7) installation and basic grammar
I wrote the basic grammar of Python with Jupyter Lab
[Note] List of basic commands for building python / conda environment
[Python] Tuple version of prefecture pull-down
Java and Python basic grammar comparison
Division of timedelta in Python 2.7 series
Python Math Series ⓪ Table of Contents
About the basics list of Python basics
Basic study of OpenCV with Python
Basic grammar of Python3 system (how to use functions, closures, lambda functions)
[Python] list
Python basic operation 1st: List comprehension notation
Display a list of alphabets in Python 3
[Basic grammar] Differences between Ruby / Python / PHP
python> Convert tuple to list> aList = list (pi_tuple)
[python] Get a list of instance variables
[Python] I personally summarized the basic grammar.
[Python Iroha] Difference between List and Tuple
Summary of built-in methods in Python list
Python Basic Course (at the end of 15)
Summary of how to use Python list
Easy introduction of python3 series and OpenCV3
[Python] Get a list of folders only
Comparing the basic grammar of Python and Go in an easy-to-understand manner
[Python / DynamoDB / boto3] List of operations I tried
Python basics: list
Introduction of Python
[python] Check the elements of the list all, any
RF Python Basic_01
[Python] Sort the list of pathlib.Path in natural sort
List type, tuple type 2
[python] Create a list of various character types
[Introduction to Udemy Python 3 + Application] 19. Copy of list
Make a copy of the list in Python
Basic Python writing
Basics of python ①