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

Get Python Data Science Essentials - Third Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.