Lists

Lists are collections of elements. Elements can be integers, floats, strings, or generically, objects. Moreover, you can mix different types together. Besides, lists are more flexible than arrays because arrays allow only a single datatype. To create a list, you can either use the square brackets or the list() constructor, as follows:

a_list = [1, 2.3, 'a', True]
an_empty_list = list()

The following are some handy methods that you will need to remember while working with lists:

  • To access the ith element, use the [] notation:
Remember that lists are indexed from 0 (zero); that is, the first element is in position 0.
a_list[1] 
# prints 2.3
a_list[1] = 2.5
# a_list is now [1, 2.5, 'a', True]
  • You can slice lists by pointing out a starting and ending point (the ending point is not included in the resulting slice), as follows:
a_list[1:3]
# prints [2.3, 'a']
  • You can slice with skips by using a colon-separated start:end:skip notation so that you can get an element for every skip value, as follows:
a_list[::2] 
# returns only odd elements: [1, 'a']
a_list[::-1]
# returns the reverse of the list: [True, 'a', 2.3, 1]
  • To append an element at the end of the list, you can use append():
a_list.append(5) 
# a_list is now [1, 2.5, 'a', True, 5]
  • To get the length of the list, use the len() function, as follows:
len(a_list) 
# prints 5
  • To delete an element, use the del statement followed by the element that you wish to remove:
del a_list[0] 
# a_list is now [2.5, 'a', True, 5]
  • To concatenate two lists, use +, as follows:
a_list += [1, 'b'] 
# a_list is now [2.5, 'a', True, 5, 1, 'b']
  • You can unpack lists by assigning lists to a list (or simply a sequence) of variables instead of a single variable:
a, b, c, d, e, f = [2.5, 'a', True, 5, 1, 'b'] 
# a now is 2.5, b is 'a' and so on

Remember that lists are mutable data structures; you can always append, remove, and modify elements. Immutable lists are called tuples and are denoted by round parentheses, ( and ), instead of the square brackets as in the list, [ and ]:

tuple(a_list) 
# prints (2.5, 'a', True, 5, 1, 'b')
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset