Knowledge Base‎ > ‎Programming‎ > ‎Python‎ > ‎Python Reference‎ > ‎

Lists

Related:

 Examples

 

 Description        

 
 Lists are variables that can hold multiple values. A list can contain any other type of variables - typically a list will hold all of the same type (but this is not required).

Lists use the square brackets for creation and accessing elements. When accessing elements you may use a single integer to obtain a single value. The index value starts at zero with the fist element. 

Using two integers such as cars[0:3] allows you to slice the list and create smaller list which just contains the elements from 0 up to (but not including) the index 3 element.

Lists can be added to, manipulated and searched using the many methods that are built into to Python, for instance: pop, insert, count, reverse, sort, index - see interpreter example below.

 Syntax

 
 

 Parameters

 

 Interpreter

 Python 2.6.5 (r265:79359, Mar 24 2010, 01:32:55) 

[GCC 4.0.1 (Apple Inc. build 5493)] on darwin

Type "help", "copyright", "credits" or "license" for more information.

>>> list 

<type 'list'>

>>> cars = ['audi','porsche','bmw','camero','civic']

>>> cars

['audi', 'porsche', 'bmw', 'camero', 'civic']

>>> cars[0]

'audi'

>>> len(cars)

5

>>> cars

['audi', 'porsche', 'bmw', 'camero', 'civic']

>>> cars.pop()

'civic'

>>> cars

['audi', 'porsche', 'bmw', 'camero']

>>> cars.index('bmw')

2

>>> cars.sort()

>>> cars

['audi', 'bmw', 'camero', 'porsche']

>>> cars.insert(0, 'golf')

>>> cars

['golf', 'audi', 'bmw', 'camero', 'porsche']

>>> cars = ['volt'] + cars

>>> cars

['volt', 'golf', 'audi', 'bmw', 'camero', 'porsche']

>>> cars.reverse()

>>> cars

['porsche', 'camero', 'bmw', 'audi', 'golf', 'volt']

>>> cars.count('bmw')

1

>>> cars.count('bmws')

0

>>> cars[0]

'porsche'

>>> cars[1]

'camero'

>>> cars[0:1]

['porsche']

>>> cars[0:2]

['porsche', 'camero']


Comments