python list
By: Ashley J Printer Friendly Format
A Python list is a mutable ordered sequence of items. The items of a list are arbitrary objects and may be of different types. To denote a list, use a series of expressions (the items of the list) separated by commas (,), within square brackets ([]); if every item is a literal, the whole assembly is a list literal. You may optionally place a redundant comma after the last item. To denote an empty list, use an empty pair of brackets. Here are some example list literals:
[42, 3.14,
'hello']
# List with three items
[100]
# List with one item
[]
# Empty list
You can also call the built-in type list to create a list. For example:
list('wow')
This builds a list equal to that denoted by the list literal:
['w', 'o', 'w']
list() without arguments creates and returns an empty list, like []. When x is iterable, list(x) creates and returns a new list whose items are the same as those x.
MODIFYING A LIST
You can modify a single item in a list by assigning to an indexing. For instance:x = [1, 2, 3, 4]
x[1] =
42
# x is now [1, 42, 3, 4]
You can also modify a range of elements in a list as below. For example:
x = [1, 2, 3, 4]
x[1:3] = [22, 33, 44] # x is
now [1, 22, 33, 44, 4]
x[1:4] = [8,
9]
# x is now [1, 8, 9, 4]
SORTING A LIST
A list’s method sort() causes the list to be sorted in-place (reordering items to place them in increasing order).
mylist = ['alpha', 'Beta', 'GAMMA']
mylist.sort()
# ['Beta', 'GAMMA', 'alpha']
mylist.sort(key=str.lower)
# ['alpha', 'Beta', 'GAMMA']
Python also provides the built-in function sorted() to produce a sorted
list from any input iterable. sorted, after the first argument (which
is the iterable supplying the items), accepts the same arguments as a
list’s method sort.Other List Operations
Method | Description |
---|---|
Nonmutating |
|
|
Returns
the number of items of |
|
Returns
the index of the first occurrence of an item in |
Mutating |
|
|
Appends
item |
|
Appends
all the items of iterable |
|
Inserts
item |
|
Removes
from |
|
Returns
the value of the item at index |
|
Reverses,
in place, the items of |
|
Sorts,
in-place, the items of |
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Subscribe to Tutorials
Related Tutorials
How to install Jupyter in Ubuntu and make it accessible through Apache Reverse Proxy
Python Basics - Setting up your Python Development Environment
What is the need for Python language?
How to compile python script and create .pyc file?
How to find the current module name in python