LinkedLists

Uncategorized

Lists

The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type.

Creating a list is as simple as putting different comma-separated values between square brackets. For example −

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

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

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

Similar to string indices, 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 you can 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.

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

Value available at index 2 :1997New 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

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

[‘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.

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, somewhat similar to an array in many other programming languages but more flexible.
  • Lists are defined in Python by enclosing a comma-separated sequence of objects in square brackets ([])

Examples:

Test = [‘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:

  • List is not merely a collection of objects. It is an ordered collection of objects. The order in which you specify the elements when you define a list is an innate characteristic of that list and is maintained for that list’s lifetime.
  • 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 can even contain complex objects, like functions, classes, and modules, which you will learn about in upcoming tutorials:

     def fun1():

     return (x=o)

     a = [int, len, fun1]

     print(a)

# output is [<class ‘int’>, <built-in function len>, <function fun1]

List Size : There is limit on the number of  Elements:

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 data items needn’t be unique:

A given data items  may  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. This is exactly analogous to accessing individual characters in a string. List indexing is zero-based as it is with strings.

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

List Indices :

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

Virtually everything about string indexing works similarly for lists.

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:

Quiz: Find  the output :

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

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 can contain sublists, which in turn may have few sublists.

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

print(x)     output is # [‘a’, [‘b’, [‘cc’, ‘dd’], ‘e’, ‘ff’], ‘g’, [5, 3], 40]

A Nested List:

To access the items in a sublist, simply append an additional index:

Quiz 2: 

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 sublists:

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])

There is no limit, short of the extent of computer’s memory, to the depth or complexity with which lists can be nested in this way

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

Lists are not recursive:

Consider what happens when we print the length of x using len():

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   #Output is False

‘dd’ in x[1]   #Output is False

 ‘dd’ in x[1][1]   #Output is 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]. An individual element in a sublist does not count as an element of the parent list(s).

Lists Are Mutable:

  • Integer or float objects, are primitive data types and immutable, meaning that they can’t be changed once they have been assigned.
  • By contrast, the 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. Python provides a wide range of ways to modify lists.

Modifying a Single List Value

A single value in a list can be 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 “<stdin>”, line 1, in <module>

TypeError: ‘str’ object does not support item assignment

List item  deletion with  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 at one time with slice assignment, which has the following syntax:

a[m:n] = <iterable>

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’]

Python grows or shrinks the list as needed.

Use appropriate slice format for 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]

Note that this is not the same as 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]

One 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 can be 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 <module>

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’].

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 can be used to modify lists. Information on these methods is detailed below.

Note: The string methods you saw in the previous tutorial did not modify the target string directly. That is because strings are immutable. Instead, 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(<obj>)

Appends an object to a list.

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

a = [‘a’, ‘b’]

a.append(123)

prnt(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

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]]

The .append() method does not work that way! 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(<iterable>)

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 <iterable> 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(<index>, <obj>)

 Inserts an object into a list

a.insert(<index>, <obj>) inserts object <obj> into list a at the specified <index>. Following the method call, a[<index>] is <obj>, 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(<obj>)

Removes an object from a list. :

a.remove(<obj>) removes object <obj> from list a. If <obj> 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:

  • You 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  <index> parameter is specified, the item at that index is removed and returned. <index> 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’]

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

Lists Are Dynamic

This tutorial began with a list of six defining characteristics of Python lists. The last one is that lists are dynamic. You have seen many examples of this in the sections above. 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

Similarly, a list shrinks to accommodate the removal of items:

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

a[2:3] = []

del a[0]

print(a)