Python Lists

Lists are just like the arrays in other languages. Lists need not be homogeneous A single list may contain different data types such as Integers, Strings, as well as Objects.  List literals are written within square brackets [ ]. Lists work similarly to strings — use the len() function and square brackets [ ] to access data, with the first element at index 0. manjor difference being list is mutable however string is not.

>>> a=[]
>>> type(a)
<class 'list'>
>>> colors = ['red', 'blue', 'green']
>>> colors[0]
>>> len(colors)
>>> colors.append('yellow')
>>> colors
['red', 'blue', 'green', 'yellow']
>>> colors.insert(0,'black')
>>> colors
['black', 'red', 'blue', 'green', 'yellow']
>>> colors.extend(['white','gre'])
>>> colors
['black', 'red', 'blue', 'green', 'yellow', 'white', 'gre']
>>> colors.pop()
>>> colors
['black', 'red', 'blue', 'green', 'yellow', 'white']
>>> colors.append('grey')
>>> colors
['black', 'red', 'blue', 'green', 'yellow', 'white', 'grey']


>>> colors[:]
['black', 'red', 'blue', 'green', 'yellow', 'white', 'grey']
>>> colors[1:1]
>>> colors[1:3]
['red', 'blue']
>>> colors[-1:]
>>> colors[-1:-1]
>>> colors[-1:-3]
>>> colors[-1:2]
>>> colors[-5:6]
['blue', 'green', 'yellow', 'white']
>>> colors[-5:-1]
['blue', 'green', 'yellow', 'white']
>>> colors[-5::-1]
['blue', 'red', 'black']

You can iterate thru list using following

>>> 'red' in colors
for col in colors:
['sky blue', 'snow white']

To check if element exists in List

>>> 'red' in colors

List Methods

Here are some other common list methods.

  • list.append(elem) — adds a single element to the end of the list. Common error: does not return the new list, just modifies the original.
  • list.insert(index, elem) — inserts the element at the given index, shifting elements to the right.
  • list.extend(list2) adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend().
  • list.index(elem) — searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear (use “in” to check without a ValueError).
  • list.remove(elem) — searches for the first instance of the given element and removes it (throws ValueError if not present)
  • list.sort() — sorts the list in place (does not return it). (The sorted() function shown later is preferred.)
  • list.reverse() — reverses the list in place (does not return it)
  • list.pop(index) — removes and returns the element at the given index. Returns the rightmost element if index is omitted (roughly the opposite of append()).

List Comprehension



Leave a Reply

Your email address will not be published. Required fields are marked *