1. Home
  2. Computing & Technology
  3. Python

Beginning Python: Data Types

From Al Lukaszewski, for About.com

8 of 10

Lists

Assigning Values to a List

A list is, as the name suggests, a series of values. In Python, these values are assigned by placing them within square braces and separating them by commas like this:

<name of list> = [ <value>, <value>, <value> ]
girls = ['sugar', 'spice', 'everything nice']
lotto = ['26', '12', '23']
addends = [4, 34, 7]
Note that 'addends' is comprised of integer variables while the others are comprised of strings, as the quotes suggest.

A list can contain any type of Python object -- even other lists.
>>> lotto[2] = addends
>>> print lotto
['26', '12', [4, 34, 7]]

Accessing the Values of List

To access a part of a list, one uses the same kind of phrase as one used for a string literal:

<name of list>[<index number>]
A few examples:
ingredient1 = girls[0]
print girls[1]
print 'brown ' + ingredient1
print girls[0] + " is not a " + girls[1]
output:
spice
brown sugar
sugar is not a spice

Combining Lists

Lists can be concatenated in a way similar to strings by using the plus operator ('+'):

primes = [1, 3, 5, 7] + [9, 11]
mishmash = girls + lotto + addends
print primes
print mishmash
output:
[1, 3, 5, 7, 9, 11]
['sugar', 'spice', 'everything nice', '26', '12', '23', 4, 34, 7]

Explore Python
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Python

©2009 About.com, a part of The New York Times Company.

All rights reserved.