LoginSignup
1
2

python リストのメソッドたち

Posted at

append

list = ['a','b','c']
list.append('d')
print(list) #['a','b','c','d']

append(x)は、リストの末尾に要素xを1つ追加します。

extend

list1 = ['a','b','c']
list2 = ['d','e','f']
list1.extend(list2)
print(list1) #['a', 'b', 'c', 'd', 'e', 'f']

extend(iterable)は、iterableのすべての要素を対象のリストに追加し、リストを拡張します。(リストを結合するイメージ)

insert

list = ['a','b','d']
list.insert(2,'c')
print(list) #['a', 'b', 'c', 'd']

insert(i, x)は、指定した位置iに要素xを挿入します。

remove

list = ['a','b','c','a']
list.remove('a')
print(list) #['b', 'c', 'a']

remove(x)は、リストの中で、xと等しい値の最初の要素を削除します。削除されるのは最初の要素だけです。(例では、2つめの'a'は削除されていない。)

pop

list = ['a','b','c']
print(list.pop()) #c
print(list) #['a', 'b']

pop([i])は、下記の2つの機能があります。
① 指定した位置iの要素をリストから取り除く
(インデックスが指定されていない場合、list.pop()はリストの末尾の要素を取り除く)
② ①で取り除いた要素を返す

clear

list = ['a','b','c']
list.clear()
print(list) #[]

clear()は、リストの中のすべての要素を取り除きます。
位置を指定して取り除きたい場合は、前述のpopを使うか、delを使います。

list = ['a','b','c']
del(list[1])
print(list) #['a', 'c']
#スライスで範囲を指定して複数の要素を一括で削除
list = ['a','b','c']
del(list[1:])
print(list)#['a']

count

list = ['a','b','c','a']
print(list.count('a'))# 2

count(x)は、リストにある要素xの数を返します。

copy

list1 = ['a','b','c']
list2 = list1.copy()
print(list2)#['a', 'b', 'c']

copy()は、リストのコピーを返します。

sort

list = ['c','a','b']
list.sort()
print(list)# ['a', 'b', 'c']

sortはリスト内の値を並べ替えます。
sorted()関数は、sortメソッドと似ていますが、リストの中身は書き換えられず、並び替えしたリストを返します。

list1 = ['c','a','b']
list2 = sorted(list1)

print(list2)# ['a', 'b', 'c']
print(list1)# ['c', 'a', 'b'] ←list1はそのまま
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2