Learn Python Fundamental in 30 Days — Day 4(Lists)

devops everyday challenge
devops-challenge
Published in
7 min readMay 4, 2017

--

  • List is an ordered sequence that contains multiple values(mutuable sequence)
  • Denoted by square brackets []
  • Contain elements(homogeneous(all integers)/mixed types(not common))
>>> x = [1,2,’abc’,2.5]>>> x[1, 2, 'abc', 2.5]
  • We can access the item in the list with an integer index that start with 0(not 1)
>>> x[0]1
  • We can use negative index to refer the last item in the list
>>> x[-1]2.5
  • To get multiple items from the list use slice
>>> x[0:2][1, 2]#Basically grab every value of the list>>> x[0:][1, 2, 'abc', 2.5]# Try to grab something out of range result an error>>> x[4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
  • List are mutable, assigning to an element at an index changes the value
>>> a = [1,2,3]
>>> a[0] = 4
>>> a
[4, 2, 3]
  • We can combine two list via concatenation(+)
>>> L1 = [1,2,3]
>>> L2 = [4,5,6]
>>> L1+L2
[1, 2, 3, 4, 5, 6]
  • All the function that works with strings works in the same way with list eg:len()
>>> len(x)4
  • To delete value from the list use del
>>> del x[0]>>> x[2, ‘abc’, 2.5]
  • To find out value in list use in operator
>>> ‘h’ in ‘hello’True#Opposite of that is not in operator>>> 'h' not in 'hello'False
  • Use of for loop with list,so as you can see for loop iterate over the values in a list
>>> for i in x:… print(i)2abc2.5
  • range() function returns a list-like value which we can pass to the list() function if we need an actual value
>>> list(range(0,4))[0, 1, 2, 3]

Let’s take one more example

>>> items = [“a”,”b”,”c”,”d”]
>>> for i in range(len(items)):
... print("Value at "+ str(i) + " is equal to: " + items[i])...Value at 0 is equal to: aValue at 1 is equal to: bValue at 2 is equal to: cValue at 3 is equal to: d

Swapping Variables

>>> a,b,c = 1,2,3>>> a1>>> b2>>> c3

Convert List to Strings or vice-versa

  • We can convert a string into a list by passing it to the list() function
>>> list(‘hello’)[‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
  • We can split() to split a string on a character
>>> s 
‘hello’
>>> s.split(‘e’)
[‘h’, ‘llo’]
# !!! Careful
>>> s.split('l')
['he', '', 'o']
  • We can use join() to turn a list of characters into a string
>>> s = [“a”,”b”,”c”]
>>> “-”.join(s)
‘a-b-c’

Lists Methods

Methods are functions that are called on values. List have several methods

  • index() list method returns the index of an item in the list
>>> test = [“a”,”b”,”c”,”d”]>>> test.index(“a”)0# Index method will raise the exception if it doesn't find the value>>> test.index("e")Traceback (most recent call last):File "<stdin>", line 1, in <module>ValueError: 'e' is not in list# Now in case of duplicate list it only return the index of first value>>> test = ["a","b","c","d","a","b"]>>> test.index("b")1
  • append() list method adds a value to the end of a list
>>> test.append(“z”)>>> test[‘a’, ‘b’, ‘c’, ‘d’, ‘a’, ‘b’, ‘z’]
  • insert() list method adds a value anywhere inside a list
>>> test.insert(0,”hola”)>>> test[‘hola’, ‘a’, ‘b’, ‘c’, ‘d’, ‘a’, ‘b’, ‘z’]
  • pop() remove element at end of list, returns the removed element
>>> L1.pop()
3
>>> L1
[1, 2]
# We can even store the value of the removed element>>> x = L1.pop()
>>> x
3
  • remove() list method removes an item,specified by the value from a list
>>> test.remove(“a”)>>> test  # Only first incident of that value is removed[‘hola’, ‘b’, ‘c’, ‘d’, ‘a’, ‘b’, ‘z’]
  • reverse(): A list can be reversed by calling its reverse() method
>>> a = [2,5,1,3,6,4]>>> a.reverse()>>> a[4, 6, 3, 1, 5, 2]
  • sort() list method sorts the items in a list(mutates the list)
>>> test1 = [8,3,9,4,6,3]>>> test1.sort()>>> test1[3, 3, 4, 6, 8, 9]

But if we want to sort a combination of numbers and strings, python throws an error as it doesn’t know how to sort it

>>> test2 = [1,2,3,”a”,”b”]>>> test2 = [1,3,2,6,5,”a”,”b”]>>> test2.sort()Traceback (most recent call last):File “<stdin>”, line 1, in <module>TypeError: ‘<’ not supported between instances of ‘str’ and ‘int’

The way sorting works is using ASCII-betical order that is upper case first

>>> test3 = [‘a’,’b’,’A’,’B’]>>> test3.sort()>>> test3[‘A’, ‘B’, ‘a’, ‘b’]

This doesn’t look good as A should followed by a,so to do that pass str.lower which is technically converting everything to lowercase

>>> test3.sort(key=str.lower)>>> test3[‘A’, ‘a’, ‘B’, ‘b’]# The important use case of key, where we use len as a key(here sorting happens based on the length)
>>> b
['hello', 'how', 'are', 'u', 'Mr', 'Prashant']>>> b.sort(key=len)>>> b['u', 'Mr', 'how', 'are', 'hello', 'Prashant']

NOTE: These list methods operate on the list “in place”,rather than returning a new list value

  • Sorted(): built-in function sorts any iterable series and return a list(does not mutate list)
>>> x = [5,2,3,1]>>> sorted(x)[1, 2, 3, 5]>>> x[5, 2, 3, 1]
  • count(): Count returns the number of matching elements
>>> a = [1,2,3,4,1,23,5,6]>>> a.count(1)2
  • extend(): To extend a list
>>> L1
[1, 2, 3]
>>> L2
[4, 5, 6]
>>> L2.extend(L1)
>>> L2
[4, 5, 6, 1, 2, 3]
# Here is the major difference between append and extend,if we use append in place of extend(nested list)>>> L1.append(L2)
>>> L1
[1, 2, 3, [4, 5, 6]]

New few things we need to be really careful about lists

>>> test = [1,2,3,4]>>> test1 = test>>> test1[1, 2, 3, 4]>>> test1[0] = 9>>> test1[9, 2, 3, 4]>>> test[9, 2, 3, 4]

We only change the value of test1 but the value of test got changed?

The Reason for that when we created this list(test), Python created this list in computer memory but it’s assigned a reference to test.Now when we run this

test1 = test

A reference get copied to test1 and they referencing the same list and that will cause all sort of weird error,so please be really careful when dealing with lists

We don’t have this kind of issues with immutable values like strings/tuples as we can’t replace it by new values

>>> a = “abc”>>> b = a>>> b = “efg”# Change in b will not impact a
>>> b
‘efg’>>> a‘abc

Let’s go much deeper into the same concept,as you see it’s just the reference which is changing here.Now we have no way to reach x = 100 so at some point of time Python garbage collector will take care of it.

  • id(): returns a unique identifier for an object
>>> x = 100>>> id(x)4340331440>>> x = 50>>> id(x)4340329840

So how to take care of this kind of issues in which we want a completely separate list, for that we have module called copy(copy has module called deepcopy which create a brand new list and return reference to new list)

>>> x = [1,2,3]>>> import copy>>> y = copy.deepcopy(x)>>> y[1, 2, 3]>>> y[0] = 4>>> y[4, 2, 3]>>> x[1, 2, 3]

OR(full slice technique)

>>> a = [4,5,6]>>> b = a[:]>>> b[4, 5, 6]>>> id(a)4325208200>>> id(b)4325208328>>> b[0] = 10>>> b[10, 5, 6]>>> a[4, 5, 6]

Some other things to note while working with lists

>>> def remove_dups(L1,L2):
… for i in L1:
… if i in L2:
… L1.remove(i)

>>> L1 = [1,2,3]
>>> L2 = [1,2,4]

Output

>>> remove_dups(L1,L2)
>>> L1 <-- This seems to be wrong it should be only 4
[2, 3]
>>> L2
[1, 2, 4]

Reason for that as Python uses internal counter to keep track of index it’s in the loop. As mutating changes the list length Python doesn’t update the counter and loops never sees the second element.To avoid these kind of issues

So better way

>>> def remove_dups(L1,L2):
… L1_copy = L1[:]
… for i in L1_copy:
… if i in L2:
… L1.remove(i)

Output

>>> L1 = [1,2,3]
>>> L2 = [1,2,4]
>>> remove_dups(L1,L2)
>>> L1
[3]
>>> L2
[1, 2, 4]

List Comprehension

Comprehensions are the Concise syntax for describing lists in a declarative or functional style.

It syntax look like this

[expr(item) for item in iterable]

Now let’s take a look at simple example

>>> y = “welcome to the world of python”.split()>>> length = []
>>> for i in y:
... length.append(len(i))
...
>>> length
[7, 2, 3, 5, 2, 6]

Now let write the same example using list comprehension

[len(x) for x in y][7, 2, 3, 5, 2, 6]

So this end of Day4, In case if you are facing any issue, this is the link to Python Slack channel https://devops-myworld.slack.com
Please send me your details
* First name
* Last name
* Email address
to devops.everyday.challenge@gmail.com, so that I will add you to this slack channel

--

--