Python Lists

Uncategorized

Lists

List is  written as a list of comma-separated values (items) between square brackets. List is that items in a list need not be of the same type.

 For example −

list1 = [‘physics’, ‘chemistry’, 1997, 2000]

list2 = [1, 2, 3, 4, 5 ]

list3 = [“a”, “b”, “c”, “d”]

list indices start at 0, and lists can be sliced, concatenated and so on.

Accessing Values in Lists

To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example:

#!/usr/bin/python 

list1 = [‘physics’, ‘chemistry’, 1997, 2000]

list2 = [1, 2, 3, 4, 5, 6, 7 ]

print “list1[0]: “, list1[0]

print “list2[1:5]: “, list2[1:5]

When the above code is executed, it produces the following result −

list1[0]:  physicslist2[1:5]:  [2, 3, 4, 5]

Updating Lists

Update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and add to elements in a list with the append() method.           For example −

#!/usr/bin/python 

list1= [‘Book1’, ‘Book2’, 1997, 2000]

print “Value available at index 2 : “

print list[2]list[2] = 2001

print “New value available at index 2 : “

print list[2]

Note − append() method is discussed in subsequent section.

Out put is−

Value available at index 2 :1997. New value available at index 2 :2001

Delete List Elements

To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know. For example −

#!/usr/bin/python list1 = [‘Book1’, ‘Book2’, 1995, 2004]

print list1del list1[2]

print “After deleting value at index 2 : “

print list1[‘Book1’, ‘Book2’, 1997, 2000]

After deleting value at index 2 :[‘Book1’, ‘Book2’, 2000]

Note − remove() method is discussed in subsequent section.

Basic List Operations

Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string.

lists respond to all of the general sequence operations .

Python Expression

Results

Description

len([1, 2, 3])

3

Length

[1, 2, 3] + [4, 5, 6]

[1, 2, 3, 4, 5, 6]

Concatenation

[‘Hi!’] * 4

[‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’]

Repetition

3 in [1, 2, 3]

True

Membership

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

1 2 3

Iteration

Python Lists:

List is a collection of arbitrary objects, similar to an array  but more flexible. 

a = [‘fun’, ‘bat’, ‘baz’, ‘ox’]

print(a) # output is [‘fun’, ‘bat’, ‘baz’, ‘ox’]

The important characteristics of Python lists are as follows:

  • Lists are ordered.
  • Lists can contain any arbitrary objects.
  • List elements can be accessed by index.
  • Lists can be nested to arbitrary depth.
  • Lists are mutable.
  • Lists are dynamic.

Lists Are Ordered

A list is not merely a collection of objects. It is an ordered collection of objects. 

Lists that have the same elements in a different order are not the same:

a = [‘fun’, ‘bat’, ‘baz’, ‘ox’]

b = [‘baz’, ‘qux’, ‘bar’, ‘foo’]

print(a == b) # output is False

print(a is b) # output is False

print([1, 2, 3, 4] == [4, 1, 3, 2]) # output is False

Lists has Arbitrary Objects:

A list can contain any assortment of objects. The elements of a list can all be the same type:

a = [21.42, ‘bar’, 3, 4, ‘bark’, False, 3.1]

print(a) # output is [21.42, ‘bar’, 3, 4, ‘bark’, False, 3.1]

Lists  contains complex objects, like functions, classes, and modules

def fun1():

        return (x=o)  

a = [int, len, fun1]

print(a)

# output is [<class ‘int’>, ,

 a = []

 print(a) # output is[]

a = [ ‘xy’ ]

print(a) # output is [‘xy’]

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print(a) # output is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

 (A list with a single object is sometimes referred to as a singleton list.)

List objects needn’t be unique. A given object can appear in a list multiple times:

a = [‘meow’, ‘woof’, ‘bark’, ‘bark’]

print(a) # output is [‘meow’, ‘woof’, ‘bark’, ‘bark’]

List Elements are accessed by Index

Individual elements in a list are  accessed using an index in square brackets.  List indexing is zero-based as it is with strings.

Example:

     a = [‘n’, ‘b’, ‘j’, ‘x’, ‘q’, ‘c’]

The indices for the elements in a are shown below:

List Indices

Use Python code to access some elements of a:

   print(a[0], a[2], a[5])

Virtually everything about string indexing works similarly for lists. For example, a negative list index counts from the end of the list:

 Negative List Indexing:

    print(a[-1], a[-2], a[-5])

If a is a list, the expression a[m:n] returns the portion of a from index m to, but not including, index n:

a = [‘n’, ‘b’, ‘z’, ‘x’, ‘q’, ‘c’]

print(a[2:5]). # output is [‘b’, ‘z’, ‘x’]

Other features of string slicing work analogously for list slicing as well:

print(a[-5:-2]) # output is [‘bar’, ‘baz’, ‘qux’]

print(a[1:4])   # output is [‘bar’, ‘baz’, ‘qux’]

print (a[-5:-2] == a[1:4]) # output is  True

Omitting the first index starts the slice at the beginning of the list, and omitting the second index extends the slice to the end of the list:

     print(a[:4], a[1:4])   # output is [‘n’, ‘b’, ‘z’] [‘b’, ‘z’, ‘z’]

      print(a[2:], a[2:len(a)])  # output is

      print(a[:4] + a[4:])   # output is

      print([a[:4] + a[4:] == a) # output is

      print(a[0:6:2])  # output is

The syntax for reversing a list works the same way it does for strings:

      printa[::-1])  # output is

The [:] syntax works for lists. However, there is an important difference between how this operation works with a list and how it works with a string.

If s is a string, s[:] returns a reference to the same object:

s = ‘funbar’

print(s[:])  # output is ‘funbar’

print(s[:] is s)   # output is True

in and not in operators:

a = [‘fun’, ‘bat’, ‘baz’, ‘qux’, ‘ux’, ‘ge’]

print(‘qux’ in a) # output is  True

print(‘td’ not in a) # output is True

The concatenation (+) and replication (*) operators:

print(a + [‘gr’, ‘ply’])

# output is [‘fun’, ‘bat’, ‘baz’, ‘qux’, ‘ux’, ‘ge”gr’, ‘ply’]

strings and lists have similar characteristics. They are both special cases of a general object type called an iterable. list is always assigned to a variable before an operation is performed on it.

print([‘f’, ‘b’, ‘z’, ‘x’, ‘qu’, ‘c’][2])

print( [‘f’, ‘r’, ‘z’, ‘qx’, ‘x’, ‘cge’][::-1])

print(‘qx’ in [‘f’, ‘r’, ‘baz’, ‘qux’, ‘qx’, ‘ce’])

Lists is Nested:

An element in a list can be any type of object. A list contains sublists, which in turn may have few sublists.

x = [‘a’, [‘b’, [‘cc’, ‘dd’], ‘e’, ‘ff’], ‘g’, [5, 3], 40]

print(x)

# [‘a’, [‘b’, [‘cc’, ‘dd’], ‘e’, ‘ff’], ‘g’, [5, 3], 40]

A Nested List

x[0], x[2] are  string list  are  and x[3] is  an int list

print(x[0], x[2], x[4]).  #  Output is a g 40

But x[1] and x[3] are sub lists:

To access the items in a sub list,  append an additional index:

x[1]     # output is

x[1][0]   # output is

x[1][1]   # output is

x[1][2]   # output is

x[3]     # output is

print(x[3][0], x[3][1])

x[1][1] is yet another sublist, so adding one more index accesses its elements:

print(x[1][1][0], x[1][1][1])

       x[1][1][-1], x[1][1:3] , x[3][::-1]

Lists are not recursive. 

x = [‘a’, [‘bb’, [‘ccc’, ‘dd’], ‘ee’, ‘ff’], ‘g’, [‘hh’, ‘ii’], ‘j’]

print(len(x)) # output is 5

print (x[1])  # out is ‘bb’, [‘ccc’, ‘dd’], ‘ee’, ‘ff’]

print(x[3])   # output is [‘hh’, ‘ii’]

x has only five elements. The individual elements in the sublists don’t count toward x’s length.

in operator in Python:

>>> ‘dd’ in x

False

>>> ‘dd’ in x[1]

False

>>> ‘dd’ in x[1][1]

True

‘dd’ is not one of the elements in x or x[1]. It is only directly an element in the sublist x[1][1]. 

 Lists are Mutable

  • Integer or float objects, are primitive data types and immutable
  • string type is a composite type. In Python, strings are also immutable.
  • The list is seen as a mutable data type. Once a list has been created, elements can be added, deleted, shifted, and moved to any place in the list. 

Modifying a Single List Value

value in a list is replaced by indexing and simple assignment:

a = [10, ‘bar’, 60, ‘qux’, ‘cor’]

print(a) [10, ‘bar’, 60, ‘qux’, ‘cor’]

a[2] = 10

a[-1] = 20

print(a) # output is [‘foo’, ‘bar’, 10, ‘qux’, 20]

Replacement of data item value is not possible with a string:

s = ‘welcome’

s[2] = ‘x’

Traceback (most recent call last):

  File “”, line 1, in

TypeError: ‘str’ object does not support item assignment

A list item is deleted with the del command:

a = [‘fun’, ‘ar’, ‘baz’, ‘qx’, ‘x’, ‘ge’]

del a[3]

print(a)  #output is [‘fun’, ‘ar’, ‘baz’, ‘x’, ‘ge’]

Modifying Multiple List Values

Python allows modifying several  elements in a list with slice assignment

a[m:n] =

a = [‘bc’, ‘bar’, ‘baz’, ‘qux’, ‘ux’, ‘ge’]

print(a[1:4])   # output is [‘bar’, ‘baz’, ‘qux’]

a[1:4] = [1.1, 2.2, 3.3, 4.4, 5.5]

print(a) # output is [‘bc’, 1.1, 2.2, 3.3, 4.4, 5.5, ‘ux’, ‘ge’]

print(a[1:6])  # output is [1.1, 2.2, 3.3, 4.4, 5.5]

a[1:6] = [‘Bark!’]

print(a)  # output is [‘bc’, ‘Bark!’, ‘quux’, ‘ge’]

Inserting  multiple elements.

a = [1, 2, 3]

a[1:2] = [2.1, 2.2, 2.3]

print(a) # output is. [1, 2.1, 2.2, 2.3, 3]

Replacing the single element with a list:

a = [1, 2, 3]

a[1] = [2.1, 2.2, 2.3]

print(a). # output is [1, [2.1, 2.2, 2.3], 3]

insert elements into a list without removing any other data items. Use  a slice format of the [n:m] at the desired index:

a = [1, 2, 7, 8]

a[2:2] = [3, 4, 5, 6]

print(a)  # output is [1, 2, 3, 4, 5, 6, 7, 8]

User can delete multiple elements any where in the list  by assigning the appropriate slice to a list.

a = [‘b’, ‘bar’, ‘baz’, ‘x’, ‘qux’, ‘ge’]

a[1:5] = []

print(a)  # output is [‘b’, ‘ge’]

a = [‘fun’, ‘b’, ‘az’, ‘q’, ‘x’, ‘cor’]

del a[1:5]

print(a) # output is [‘fun’, ‘cor’]

Appending Items to a List:

Additional items are added to the start or end of a list using the +concatenation operator or the += augmented assignment operator:

a = [‘fun’, ‘b’, ‘az’, ‘qux’, ‘x’, ‘cor’]

a += [‘gra’, ‘ply’]

print(a) # output is [‘fun’,’b’,’az’,’qux’, ‘x’,’cor’, ‘gra’,’ply’]

a = [‘fun’, ‘b’, ‘az’, ‘qux’, ‘x’, ‘cor’]

a = [10, 20] + a

print(a) # output is [10,20,’fun’, ‘b’, ‘az’, ‘qux’, ‘x’, ‘cor’]

a += 20

Traceback (most recent call last):

  File “<pyshell#58>”, line 1, in

    a += 20

TypeError: ‘int’ object is not iterable

a += [20]

print(a).  # output is [10,20,’fun’, ‘b’, ‘az’, ‘qux’, ‘x’, ‘cor’,20]

a = [‘o’, ‘bar’, ‘baz’]

a += ‘corge’

print(a) #output is [‘o’, ‘bar’, ‘baz’, ‘c’, ‘o’, ‘r’, ‘g’, ‘e’]

To add the single string ‘corge’ to the end of the list, we need to specify it as a singleton list:

a = [‘o’, ‘bar’, ‘baz’, ‘qux’, ‘x’]

a += [‘cge’]

print(a)  # output is [‘o’, ‘bar’, ‘baz’, ‘qux’, ‘x’, ‘cge’]

Methods that Modify a List

Python supplies several built-in methods that are used to modify lists. 

Note: string methods return a new string object that is modified as directed by the method. They leave the original target string unchanged:

s = ‘xyz’

t = s.upper()

print(s, t).  # output is xyx, XYZ

List methods are different. Because lists are mutable, the list methods shown here modify the target list in place.

a.append()

Appends an object to a list.

a.append() appends object  to the end of list a:

a = [‘a’, ‘b’]

a.append(123)

print(a)  # output is [‘a’, ‘b’, 123]

list methods modify the target list in place. They do not return a new list:

a = [‘a’, ‘b’]

x = a.append(123)

print(x) # output is None

print(a)  # output is [‘a’, ‘b’, 123]

Remember that when the + operator is used to concatenate to a list, if the target operand is an iterable, then its elements are broken out and appended to the list individually:

a = [‘a’, ‘b’]

print((a + [1, 2, 3])) # expected output is [‘a’, ‘b’, [1, 2, 3]]

If an iterable is appended to a list with .append(), it is added as a single object:

a = [‘a’, ‘b’]

a.append([1, 2, 3])

print(a)   # output is [‘a’, ‘b’, [1, 2, 3]]

a = [‘a’, ‘b’]

a.append(‘temp’)

print(a)  #  output is [‘a’, ‘b’, ‘temp’]

a.extend()

Extends a list with the objects from an iterable.

.extend() also adds to the end of a list, but the argument is expected to be an iterable. The items in  are added individually:

a = [‘a’, ‘b’]

a.extend([1, 2, 3])

print(a)  # output is [‘a’, ‘b’, 1, 2, 3]

.extend() behaves like the + operator. More precisely, since it modifies the list in place, it behaves like the += operator:

a = [‘a’, ‘b’]

a += [1, 2, 3]

print(a)  # output is [‘a’, ‘b’, 1, 2, 3]

a.insert(, )

Inserts an object into a list

a.insert(, ) inserts object  into list a at the specified . Following the method call, a[] is , and the remaining list elements are pushed to the right:

a = [‘f’, ‘b’, ‘z’, ‘q’, ‘ux’, ‘cor’]

a.insert(3, 3.14159)

print(a) # output is [‘f’, ‘b’, ‘z’, 3.14159,’q’, ‘ux’, ‘cor’]

a.remove()

Removes an object from a list :

a.remove() removes object  from list a. If  isn’t in a, an exception is raised:

a = [‘f’, ‘b’, ‘a’, ‘q’, ‘x’, ‘c’]

a.remove(‘b’)

print(a).  output is [‘f’, ‘a’, ‘q’, ‘x’, ‘c’]

a.pop(index=-1)

Removes an element from a list.

This method differs from .remove() in two ways:

  • specify the index of the item to remove, rather than the object itself.
  • The method returns a value: the item that was removed.

a.pop() simply removes the last item in the list:

a = [‘f’, ‘b’, ‘a’, ‘u’, ‘x’, ‘c’]

a.pop()    # output is c

print(a)   #  output is [‘f’, ‘b’, ‘a’, ‘u’, ‘x’]

If   parameter is specified, the item at that index is removed and returned.  may be negative, as with string and list indexing:

a.pop(1)

print(a)     #  output is [‘f’, ‘a’, ‘u’, ‘x’]

a.pop(-3)  #  output is [‘f’,’u’, ‘x’]

 defaults to -1, so a.pop(-1) is equivalent to a.pop().

Lists are Dynamic

When items are added to a list, it grows as needed:

a = [‘f’, ‘b’, ‘a’, ‘q’, ‘u’, ‘c’]

a[2:2] = [1, 2, 3]

a += [3.14159]

print(a) # output is ‘f’, ‘b’, ‘a’, 1, 2, 3, ‘q’, ‘u’, ‘c’, 3.14159

 list shrinks to accommodate the removal of items:

a = [‘f’, ‘b’, ‘a’, ‘q’, ‘u’, ‘c’]

a[2:3] = []

del a[0]

print(a)