Introduction To Python Lists
Tags: python, list, datastructures
Published: 2018-04-30 13:28:09

---
title: Introduction To Python Lists
published: true
tags: Python, List,Data-structures
canonical_url: 
---

![](https://thepracticaldev.s3.amazonaws.com/i/1r60jwep68i2y5c0vg16.jpg)

List is the most versatile python data structure and stores an ordered sequence of elements just like your shopping list or to-do-list.In Python, Lists are <code>mutable</code>,meaning that the elements can be altered unlike <code>tuples</code> or even <code>strings</code>.These elements of  a <code>list</code> are called <code>items</code> and can be any data type.
### Creating Lists in Python 
Creating lists in python is quite simple, use square brackets [] and separate items in the list with commas.
A list can be empty or contain any number of items with different data types  (integers,float,strings etc.).

    mylist = [ ]  #empty list
    mylist2 = [1,2]  # list containing 2 items with integers
    mylist3 = [1, 2, 'hello']  # list with 3 items,mixed data types,integers and a string
 <srtong>Note</strong> : a  list can also hold another list as an item,these are called <code>nested lists.</code> as show below.

    mylist4 = [['python','php'],[1,2,3]  # a nested list

### Accessing items in a list
We can access items in a list by 

1. **Indexing**.
We use the <code>index</code> operator [ ].Each item in a list has an assigned index value. It is important to <strong>Note</strong> that the  index starts from 0 in python and **must** be an integer
<table class="table">
<thead class=" thead-light">
<tr>
<th scope="col">java</th>
<th scope="col">python</th>
<th scope="col">perl</th>
<th scope="col">ruby</th>
<th scope="col">c#</th>
</tr>
</thead><tbody>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
</tbody></table>
<strong>Note</strong> :The first item of any non-empty list is [0].

        Languages = ['java', 'python', 'perl' 'ruby', 'c#' ]   # define a list
        print(Languages[0]) # Access the first item of a list at index 0
        # Output:java which is the first item on the list.

        
2. **Negative Indexing** Python also  supports  negative indexing.The negative indexing  is useful when you want to  get the last item in a list because it start accessing a list  from the end.
<table class="table">
<thead class=" thead-light">
<tr>
<th scope="col">java</th>
<th scope="col">python</th>
<th scope="col">perl</th>
<th scope="col">ruby</th>
<th scope="col">c#</th>
</tr>
</thead><tbody>
<tr>
<td>-5</td>
<td>-4</td>
<td>-3</td>
<td>-2</td>
<td>-1</td>
</tr>
</tbody></table>
><strong>Note</strong>:The last item of any non-empty list is [-1].

        # define a list 
        Languages = ['java', 'python', 'perl' 'ruby', 'c#' ] 
         print(Languages[-1) #Access the last item of a list
        # Output:  C#

**length of list**

Python has useful in-built functions that work with list.We will discuss them later but for now, <code>len()</code> function help us in returning the total number of elements in a list.

    # define a list
    languages = ['java', 'python' ,'perl', 'ruby', 'c#']
    # print the length of the list
    print(len(languages)) 
    # output 5
### Slicing of a List
Slices are good for getting a subset of items in a list.It uses the <code>slicing</code> operator : (colon) to extract part of the sequence.

    Languages = ['java', 'python', 'perl','ruby', 'c#' ] # define a list 
    # [:3] slicing everything up to but not including index 3
    print(languages[:3])  
    #Outputs: ['java', 'python', 'perl' ]

    # define a list 
    Languages = ['java', 'python', 'perl','ruby', 'c#' ]
    # [3:] slicing everything from index 3 to the last item
    print(languages[3:])
    #Output: ['ruby', 'c#' ]
  

    Languages = ['java', 'python', 'perl','ruby', 'c#' ]
    #elements from beginning to end
    print(languages[:])
    #Output: ['java', 'python', 'perl','ruby', 'c#' ]

    # define a list 
    Languages = ['java', 'python', 'perl','ruby', 'c#' ]
    # elements from 1st to 3rd
    print(languages[0:3])
    Output # ['java', 'python', 'perl']

### How to  change/add elements in a list
**list.append(item)**

The method <code>list.append(item)</code> will add the <code>item</code> at  the end of a list.

       # define a list
       languages = ['java', 'python' ,'perl', 'ruby', 'c#']
       # append c
       languages.append('c') 
       print (languages)
      # Output : ['java', 'python', 'perl', 'ruby', 'c#', 'c']
       
**list.insert(i, item)**

This method  will insert an item at the ith position in a list , shifting elements to the right.

    # define a list
    languages = ['java', 'python' ,'perl', 'ruby', 'c#']
    # insert c
    languages.insert( 0, 'php') 
    print languages 
    # Output :  ['php', 'java', 'python', 'perl', 'ruby', 'c#']

**list.extend(items)**

The extend method concatenates lists. Note that you do not call extend with multiple arguments;it takes  in a second list as its argument.

    # define a list
    languages = ['java', 'python' ,'perl', 'ruby', 'c#']

    Languages2=['c++', 'c'] # define a second list

    languages.extend(Languages2)

    print(languages)

    # Output ['java', 'python', 'perl', 'ruby', 'c#', 'c++', 'c']

> extend method does not return any value,instead it modifies the original list by adding the content of the second list
    


### Deleting List Elements
Use the **del** keywords to delete an item at specific index

+ single item

         languages = ['java', 'python' ,'perl', 'ruby', 'c#'] # define a list
         del languages[2] # use del keyword
         print(languages)
         # Output removes perl ['java', 'python', 'ruby', 'c#']

+ Multiple items

         languages = ['java', 'python' ,'perl', 'ruby', 'c#'] # define a list
         del languages[1:3]  #delete Multiple items by slicing
         print(languages)

         # Output : ['java', 'ruby', 'c#'] 

**list.remove(item)**

It will search and  remove <code>only</code> the first occurrence  of an item 

    Languages = ['java', 'python', 'perl','python','ruby', 'c#' ]
    Languages.remove('python')  # the first occurrence of python
    print(languages) # outputs ['java', 'perl', 'python', 'ruby', 'c#']

   It removes the python after java'.Note that the 'python' after perl is still present

**list.pop()**

Removes and returns the last item of a list


    languages = ['java', 'python' ,'perl', 'ruby', 'c#']

    print(languages.pop()) # print c#

    print(languages)
    # output ['java', 'python', 'perl', 'ruby']
   
 
**list.pop(i)**

Removes and returns the ith item of a list

    Languages = ['java', 'python', 'perl','ruby', 'c#' ]
    print(languages.pop(1)) # removes  index 1 item
    #  Output returns Python


**list.index(item)**

When lists start to get long, it becomes more difficult for us to count out our items to determine at what index position a certain value is located. We can use <code>list.index(item)</code>,  to return the index in the list where that item is located. 
If there is more than one item with value  <code>item</code>, this method will return   the first occurrence.

### Summary of  list methods

<table>
  <thead>
    <tr>
       <th></th>
      <th>Method Name</th>
       <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>1</th>
      <td>alist.append(item)</td>
      <td>Adds a new item at the end of the list</td>
    </tr>
    <tr>
      <th>2</th>
      <td>alist.insert(i, item)</td>
      <td>Insert item at the ith position shifting other items to the right.</td>
    </tr>
        <tr>
      <th>3</th>
      <td>alist.extend()</td>
      <td>Adds the elements  of a second list to the original list</td>
   </tr>
    <tr>
      <th>4</th>
      <td>del alist[i]</td>
      <td>Deletes the item at the ith position,it can also a range of items by the use of slicing</td>
   </tr>
    <tr>
      <th>5</th>
      <td>alist.remove(item)</td>
      <td>Search and remove the first occurrence of an item,does not return a new list and throws an error if not found</td>
   </tr>
    <tr>
      <th>6</th>
      <td>pop()</td>
      <td>Removes and returns the last item of a list</td>
   </tr>
    <tr>
      <th>7</th>
      <td>pop(i)</td>
      <td>Removes and returns the i item of a list</td>
   </tr>
    <tr>
      <th>8</th>
      <td>alist.index(item)</td>
      <td>Returns the index of first occurrence</td>
   </tr>
    <tr>
      <th>9</th>
      <td>alist.sort()</td>
      <td>sort the items of a list</td>
   </tr>
    <tr>
      <th>10</th>
      <td>alist.reverse()</td>
      <td>Reverses a List</td>
   </tr>
    <tr>
      <th>11</th>
      <td>alist.count(item)</td>
      <td>Returns the  count of occurrence of an item</td>
   </tr>
  </tbody>
</table>

### Common List Operations

**Concatenation**

Concatenation uses the  <code> + </code> Operator. It Combines lists. 

    # define a list
    languages = ['java', 'python' ,'perl', 'ruby', 'c#']
    print(languages +(['c++', 'c']))
    # Output:  ['java', 'python' ,'perl', 'ruby', 'c#', c++, c]

**Repetition**

 uses the  <code> * </code> Operator. Concatenates a list a repeated number of times

     mylist = ['strings are  cool'] * 2
     print (mylist)
    # output:  ['strings are  cool', 'strings are  cool']

**Membership**

Keyword <code>In</code>  is used to test if an item is  a member of a  list.

    languages = ['java', 'python' ,'perl', 'ruby', 'c#']
    if 'python' in languages:
        print('right')



### Iteration
<code>For</code> Loop is used to iterate through each element on a list with the keyword  <code>in</code>.The for loop allows you to to perform an action for every element in the list.

**illustration 1**

    languages = ['java', 'python' ,'perl', 'ruby', 'c#']
    for i in languages:
       print(i)
This will print the all the items in the list one per line as shown below:
    
    java
    python
    perl
    ruby
    c#
**illustration 2**

    random_sum = [2,7,8,9]
    total = 0
    for i in random_sum:
        total +=i
    print total

The above code will print 26,the sum of all the items of the list.
The for loop requires a variable to hold the items being iterated and the source.


<code>While</code> Loop will first check the condition .If the condition is <code>true</code>,it will keep iterating and terminates the loop  once the condition turns <code>false</code>.

    languages = ['java', 'python' ,'perl', 'ruby', 'c#']
    i = 0
    while i <len(languages):
        print(languages[i])
        i = i+3
The above codes will print 

    java
    ruby


### Conclusion
 Now you know what lists are and how to manipulate them.For further understanding on list, read  about list comprehension.