Python: List Tutorial

, , …,

List Basics

Creating List

[item 0, item 1, item 2, ]

# -*- coding: utf-8 -*-
# python

a = [0, 1, 2, "m", 4, 5]
print a # [0, 1, 2, 'm', 4, 5]

Count Elements

len(list)

# -*- coding: utf-8 -*-
# python

# Get length
a = ["more", 4, 6]
print len(a)        # prints 3

Get a Element

List element can be extracted with the form list[index].

# -*- coding: utf-8 -*-
# python

# get one element
a = ["more", 4, 6]
print a[1]          # prints 4

Negative index counts from right.

# -*- coding: utf-8 -*-
# python

a = ["more", 4, 6]
print a[-1]         # prints 6

# negative index counts from right

Change a Element

A element can be changed with the form list[index] = new value.

# -*- coding: utf-8 -*-
# python

a = ["zero", "one", "two"]
a[2] = "b"
print a                 # prints ['zero', 'one', 'b']

Delete a Element

Use the “del” statement: del list[index].

# -*- coding: utf-8 -*-
# python

a = ["zero","one","two","three"]
del a[2]
print a                         # ['zero', 'one', 'three']

Get Sublist

Sublist can be extracted using the form list[start index:end index]. (warning: end index element is not included. For example, mylist[1:2] returns only 1 elements, not 2.)

# -*- coding: utf-8 -*-
# python

a = ["zero", "one", "two", "three", "four", "five"]
print a[1:4]        # ⇒ ['one', 'two', 'three']

# if first index is ommited, default to 0
print a[:4]         # ⇒ ['zero', 'one', 'two', 'three']

# if second index is ommited, default length of list. Effectively, up to last element
print a[0:]         # ⇒ ['zero', 'one', 'two', 'three', 'four', 'five']

# get everything
print a[:]         # ⇒ ['zero', 'one', 'two', 'three', 'four', 'five']

# negative counts from last. Not include last.
print a[0:-1]       # ⇒ ['zero', 'one', 'two', 'three', 'four']

Change Sublist

A slice (sublist) of elements can be changed by assigning to a list directly. The length of the slice need not match the length of new list.

list[index1:index2] = new list → replace a sublist by new list.

# -*- coding: utf-8 -*-
# python

a = [0, 1, 2, 3, 4, 5]
a[2:4] = ["a", "b"]
print a                    # [0, 1, 'a', 'b', 4, 5]

Nested Lists

Lists can be nested arbitrarily. Append extra bracket to get element of nested list.

# -*- coding: utf-8 -*-
# python

a = [3, 4, [7, 8]]
print a
print a[2][1]    # returns 8

Join 2 Lists

Lists can be joined with plus sign.

# -*- coding: utf-8 -*-
# python

b = ["a", "b"] + [7, 6]
print b      # prints ['a', 'b', 7, 6]

5. Built-in Types — Python v2.7.6 documentation #mutable-sequence-types

List Methods

Python: List Methods

blog comments powered by Disqus