Lists In Python

This page is an overview on lists in Python. Sections include:

  • What Is A List In Python?
  • Examples Of Lists
  • The Repetition Operator
  • Length Of A List With len()
  • Indexing In A List
  • Changing Elements In A List (Mutability)

 


What Is A List In Python?

A list is an object which holds different data items. Since lists are mutable, the contents in a list can be changed.

Items in a list are called elements. Each element has its own index. The indices start from the left at 0 and count up by 1 to the length of the list minus one.

 


Examples Of Lists

Lists can store different data types. The first list stores numbers, the second one stores strings and the last one stores a mixture contains two numbers, a string and a boolean value of True.

 

 

 


The Repetition Operator

For repeating the same elements in a list, you can use the repetition operator. This operator is simply an asterisk * which is for multiplication. The format is list * n where n is the number of times you want the list to repeat.

 

 

 


Length Of A List With len()

To find out how many elements there are in a list, the len() function comes in handy.

 

 


Indexing In A List

Elements in a list can be accessed by its index. A list’s index starts from 0 which is associated with the first item of the list (from the left).

 

 


Changing Elements In A List (Mutability)

In lists, mutability means that elements in a list can be changed. Referring to the example below, the first element of 1 is changed into a 5 and the True as the last element (index 3) is changed to False.

 

 

 


Concatenating Lists

Concatenating is a long and fancy way of saying combine. Lists can be combined with the addition sign (+). In the example below, the lists a and b can be added together to obtain one longer list.

 

 


A For Loop With A List

You can use a for loop with a list. Keep in mind that the range() function is not used for this type of for loop. In the example below the counter i refers to the element in the list. The loop goes from the first element (index 0) to the last element.

 

 


List Slicing

With list slicing, you can obtain a selection/subset from the larger list. The format is:

This will obtain the elements in the list from the index of start to the element with the index of end – 1. It does not include the index at end.

 

 

 


The in Keyword

Along with the if statements, the in keyword is useful for determining if something is in a list or not.

 

 

 


The append Keyword

To add new elements into a list, use the append keyword with .append after the list object name. In the example, four more square numbers are added to the list of square numbers.

 

 

Leave a Reply