What is list data structure in Python

Get to know list data structure

List is a sequence of data and list is a structure which can be changed.

Tuple is a sequence of data and cannot be change.

Lists are useful when you want to work with a collection of values. The items of a list are separated by commas and enclosed in square brackets.

A list can contain other lists. An empty list is simply written as two brackets, [].

None is a Python value and means nothing. To initialize a list of length 10, you could do the following:


sequence = [None] * 10 
print sequence 

The code above generates the following result.

MethodDescription
list.append(object) Add to the end of a list.
list.count(object) Returns the number of i's for which list[i] == object.
list.extend(sequence)Equivalent to list[len(list):len(list)] = sequence.
list.index(object) Returns the smallest i for which list[i] == object (or raises a ValueError if no such i exists).
list.insert(index, object)Equivalent to list[index:index] = [object] if index >= 0; if index < 0, object is prepended to the list.
list.pop([index]) Removes and returns the item with the given index (default -1).
list.remove(object) Equivalent to del list[list.index(object)].
list.reverse() Reverses the items of list in place.
list.sort([cmp][, key][, reverse]) Sorts the items of list in place (stable sorting). Can be customized by supplying a comparison function, cmp; a key function, key, which will create the keys for the sorting); and a reverse flag (a Boolean value).

Nested List

The following code creates a list q first and then use q as one element to create p. Now List p is a nested listed.


q = [2, 3]# from   w ww.jav  a2 s. co  m
p = [1, q, 4]

print len(p)

print p[1]

print p[1][0]

p[1].append('xtra')

print p

print q

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print matrix[1]
print matrix[1][1]
print matrix[2][0]

The code above generates the following result.

List for iteration


for x in [1, 2, 3]: print x,      # iteration

The code above generates the following result.

For Statements


a = ['cat', 'window', 'defenestrate']
for x in a:
     print x, len(x)

The code above generates the following result.

Loop through a list: for in


a = ['cat', 'window', 'defenestrate']
#   w w  w .  ja  v  a 2s.  c  om
for x in a[:]: # make a slice copy of the entire list
    if len(x) > 6: a.insert(0, x)
 
print a

The code above generates the following result.

To iterate over the indices of a sequence, combine range() and len().


a = ['Mary', 'had', 'a', 'little', 'lamb']

for i in range(len(a)):
     print i, a[i]

The code above generates the following result.





















Home »
  Python »
    Data Types »




Data Types
String
String Format
Tuple
List
Set
Dictionary