Python: List Basics

By Xah Lee. Date: . Last updated: .

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

If you have a question, put $5 at patreon and message me.

Python by Example

  1. Python Basics
  2. Print Version String
  3. Builtin Help
  4. Quote String
  5. String Operations
  6. String Methods
  7. Format String
  8. True, False
  9. if then else
  10. for, while, Loops
  11. List Basics
  12. Loop Thru List
  13. Map Function to List
  14. List Comprehension
  15. List Methods
  16. Dictionary
  17. Loop Thru Dict
  18. Dict Methods
  19. Function
  20. Class
  21. List Modules
  22. Write a Module
  23. Unicode 🐍

Regex

  1. Regex Basics
  2. Regex Reference

Text Processing

  1. Read/Write File
  2. Traverse Directory
  3. Manipulate Path
  4. Process Unicode
  5. Convert File Encoding
  6. Find Replace in dir
  7. Find Replace by Regex
  8. Count Word Frequency

Web

  1. Send Email
  2. GET Web Page
  3. Web Crawler
  4. HTTP POST
  5. Check Page Load Size
  6. Thumbnail Generation

Misc

  1. JSON
  2. Find Script Path
  3. Get Env Var
  4. System Call
  5. Decompress Gzip
  6. Complex Numbers

Advanced

  1. Sort
  2. Copy Nested List
  3. Tuple vs List
  4. Sets, Union, Intersection
  5. Closure in Python 2
  6. Decorator
  7. Append String in Loop
  8. Timing f timeit
  9. Keyword Arg Default Value Unstable

Reference