DEV Community

Jadieljade
Jadieljade

Posted on

Introduction to python: Lists

We all know python as a general purpose language designed to be very efficient in writing and especially to read. Python however is also an uncomplicated and robust programming language that delivers both the power and complexity of traditional style. What makes it so powerful is its extensive library and the amazing data types it brings to the game.

Some built-in Python data types are:

  • Numeric data types: int, float, complex
  • String data types: str
  • Sequence types: list, tuple, range
  • Binary types: bytes, bytearray, memoryview
  • Mapping data type: dict
  • Boolean type: bool
  • Set data types: set, frozenset

In todays article we are going to focus on a lists in python looking at the amazing stuff you can do with them.

A list is a built-in data structure used to store multiple items in a single variable. It is an ordered collection of elements enclosed in square brackets [], where each element is separated by a comma.

Lists are versatile and can contain elements of different types, such as integers, floats, strings, or even other lists. They are mutable, which means you can modify them by adding, removing, or changing elements after they are created.

as previously stated list literals are defined within square brackets []. Similar to strings we can use the len() function to get the sum total of the number of items in the list.

  colors = ['red', 'blue', 'green']
  print(colors[0])    ## red
  print(colors[2])    ## green
  print(len(colors))  ## 3
Enter fullscreen mode Exit fullscreen mode

The = sign is the assignment operator.
When it comes to arithmetic operations only multiplacation happens within a list.

colors=['red','blue']
doublecolors=colors*2
print(doublecolors)  ## ['red', 'blue', 'red', 'blue']
Enter fullscreen mode Exit fullscreen mode

Iteration.
Now with items in the list if we wanted to go through the items individually we iterate through them.
Python's for and in constructs are extremely useful in this case. The for construct -- for var in list -- is an easy way to look at each element in a list (or other collection). Do not add or remove from the list during iteration.

  squares = [1, 4, 9, 16]
  sum = 0
  for num in squares:
    sum += num
  print(sum)  ## 30
Enter fullscreen mode Exit fullscreen mode

If you know what sort of thing is in the list, its good practice to use a variable name in the loop that captures that information such as "num", or "name", or "url".

The in construct on its own is an easy way to test if an element appears in a list (or other collection) -- value in collection -- tests if the value is in the collection, returning True/False.

list = ['larry', 'curly', 'moe']
  if 'curly' in list:
    print('yay')
Enter fullscreen mode Exit fullscreen mode

The for/in constructs are very commonly used in Python code and work on data types other than list.

While Loop
for/in loops are great at iterating over every element in a list, the while loop however gives you total control over the index numbers. Here's a while loop which accesses every 3rd element in a list:


  ## Access every 3rd element in a list
  i = 0
  while i < len(a):
    print(a[i])
    i = i + 3
Enter fullscreen mode Exit fullscreen mode

Range
The range(n) function yields the numbers 0, 1, ... n-1, and range(a, b) returns a, a+1, ... b-1 -- up to but not including the last number. The combination of the for-loop and the range() function allow you to build a traditional numeric for loop:

 ## print the numbers from 0 through 99
  for i in range(100):
    print(i)
Enter fullscreen mode Exit fullscreen mode

List Build Up
One common pattern is to start a list as the empty list [], then use append() or extend() to add elements to it:


  list = []          ## Start as the empty list
  list.append('a')   ## Use append() to add elements
  list.append('b')
Enter fullscreen mode Exit fullscreen mode

List Slices
Slices work on lists just as with strings, and can also be used to change sub-parts of the list.

list = ['a', 'b', 'c', 'd']
  print(list[1:-1])   ## ['b', 'c']
  list[0:2] = 'z'    ## replace ['a', 'b'] with ['z']
  print(list)         ## ['z', 'c', 'd']



Enter fullscreen mode Exit fullscreen mode

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

Notice that these are methods on a list object, while len() is a function that takes the list (or string or whatever) as an argument.

  list = ['larry', 'curly', 'moe']
  list.append('shemp')         ## append elem at end
  list.insert(0, 'xxx')        ## insert elem at index 0
  list.extend(['yyy', 'zzz'])  ## add list of elems at end
  print(list)  ## ['xxx', 'larry', 'curly', 'moe', 'shemp', 'yyy', 'zzz']
  print(list.index('curly'))    ## 2

  list.remove('curly')         ## search and remove that element
  list.pop(1)                  ## removes and returns 'larry'
  print(list)  ## ['xxx', 'moe', 'shemp', 'yyy', 'zzz']
Enter fullscreen mode Exit fullscreen mode

Common error: note that the above methods do not return the modified list, they just modify the original list.

  list = [1, 2, 3]
  print(list.append(4))   ## NO, does not work, append() returns None
  ## Correct pattern:
  list.append(4)
  print(list)  ## [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Thank you for the read.

Top comments (0)