Python Lists in under 10 minutes
Tags: python, tutorial, beginners
Published: 2020-08-08 11:41:36

In the previous [post](https://dev.to/gothamv/python-strings-in-under-10-minutes-1e70), we discussed about the String data type. In this post let’s discuss the List data type. List is an ordered collection data type. It’s like an array. Think of it as a variable but instead of a single value you can store multiple values in it. And the values inside these lists can be a combination of numbers, strings, or lists(list inside a list) etc. Lists are indexable and they support slicing as well. Let’s learn all about them!

### Declaring a variable of the List Type:

The syntax for list : variableName = []. And inside these square brackets, we add the values we want separated by commas. The following example will make things clear.

    myList = [1, 2, 3, 4, 5] #This is list
    print(type(myList))

We can store any type of value inside a list. For example, we can store a list of strings. Or we can create a list with both numbers and strings. Or we can even have a list inside a list.

```
    myList2 = ["Hello", "This", "Is", "A", "List"]
    myList3 = ["A", "List", "can also contain numbers", 1, 2, 2.2]
    print(type(myList2))
    print(type(myList3))
```

Run the code below and check it out:

{% replit @Gothamv/lists %}

### You can combine two lists by using the + sign:

Paste the code below in the repl window above and run it.

    myList = [1, 2, 3]
    myList2 = [4, 5]
    myList3 = myList + myList2

So now myList3 will contain [1, 2, 3, 4, 5] . Same goes for lists consisting of a combination of multiple data types. It just adds the list to the right of the + operator to the list on the left of the + operator.

### Accessing elements in the list:

Because Lists are an ordered sequence of data items we can index them. Just like in Strings. You can access elements inside the list using a method called **Indexing**. Meaning **every data item in the list has a number associated with it**. Using these numbers we can grab parts of the list and we can manipulate them without affecting the original List. All you have to do is pass in the position of the element you want to access to the list. It is important to note that the position of elements in a list or any data type that is indexable starts with 0. Let’s look at an example.

    myList = [1, 3, "Four", 5, "Six", 7]

### A List can be indexed in two ways:

1: Positive Indexing

2: Negative or reverse indexing

![myList indexing](https://cdn-images-1.medium.com/max/7264/1*f-Dsp2GrZmMZqwpYl9StBw.jpeg)*myList indexing*

### 1: Positive Indexing:

In positive indexing, the list is numbered from **left to right starting with 0**. Yes 0. You start numbering from 0. So **0 will the index value of the first data item** in the list, 1 will be the index value of the second item in the list and so on …

### 2: Negative Indexing:

In negative indexing, the list is numbered from the **right to left start with negative 1**. So -1 will the be the index of the first item from the right and you increment as you go on …

### So to grab a data item from the list:

Syntax : listName[index]

    a = myList[0]  # stores 1 in a 
    b = myList[5]  # stores 7 in b
    c = myList[-1] # stores 7 in c
    d = myList[-2] # stores 'Six' in d

{% replit @Gothamv/list2 %}

Now, what if we wanted to access multiple items in the list at once?

### Accessing elements in the list using Slicing:

Using slicing we can use **indexing**to grab multiple items of the list. Here’s the Syntax : listName[startIndex : stopIndex].

The **stop index is excluding** meaning it’ll grab the items only until the stop index but not including the character at the stop index. The **start index is inclusive of the item at the start index**. Run the code below.

{% replit @Gothamv/list3 %}

If you don’t understand the code above learn more about slicing in detail check out my [previous post]((https://dev.to/gothamv/python-strings-in-under-10-minutes-1e70)) on Strings where I explain the very same in-depth. Negative Slicing alone doesn’t work as expected with slicing in lists. Negative indexing is possible and will work just fine. Just not negative slicing.

### Adding elements to the list:

Now if we want to add elements to the list we can use the methods append(), insert() and extend().

1: **append():**

Using append we can add a single element at the end of the list. 
In the append() method you simply pass the element to it.
> We’ll learn more about what passing means when we learn about functions in python. For now, think of it as sending something to this line of code which in-turn makes use of some other lines of code which python knows by default.

If it is just numbers you don’t have to bother about the ‘’ . If it is a character or a string you must enclose it in a ‘’ or “”.

```
    myList = [1]
    myList.append(2)
```

2: **insert():**

Using the insert() method we can add elements at a specific index in the list.
In the insert() method we pass in the index (position) we want to add the element followed by the actual element. This will add the element at the specified index pushing the other elements in the list towards the right.
`
    myList1 = [1, 3, 4, 5]
    myList1.insert(1, 2)

3: **extend():**

In the extend() method we need to pass the elements to it as another list (in [] separated by commas).

    myList2 = ["Hello"]
    myList2.extend(["World", "!"])

If you just pass in using ‘’ or “” it’ll add each character of the element as a new item on the list you are performing the method on.

    myList3 = ['H', 'E', 'L']
    myList3.extend('LO')

Run the code below to see the output of the above code.

{% replit @Gothamv/lists2 %}

### Deleting elements from the list:

Now if we want to delete elements from the list we can use the pop(), del() or the remove() methods.

1: **pop():**

The pop() method will remove a single element from the end of the list each time it is used. You can optionally pass the index to the pop() method to delete elements at a particular index.

    myList = [1, 2, 2, 3, 4, 5, 5]
    myList.pop()

2: **del():**

Using the del() method we can delete an element at a specific index. You need to pass the index of the element you want to delete to it. The del() syntax is a little different. We use del Listname[index]. The only difference between del() and pop() is that pop() returns the element that is being deleted while the del() does not.

    del myList[5]

3: **remove():**

And using the remove() we can remove the first occurrence of the element in the list. Meaning if the list1 has [1,2,3,2,4] using remove(2) on it deletes the 2 at index 1 and not the one index 3 as well. It stops after deleting the first occurrence the element you pass to it.

    myList.remove(2)

{% replit @Gothamv/lists3 %}

### Bonus operations on List:

There are a few additional useful methods that you can apply to Lists such as sort(), reverse(), extend() and index().

1: **sort():**

If your list consists of numbers you can use the sort method to store the numbers in the list in ascending or descending order. Same goes for strings in the list(based on the first character of the string). This ascending/descending order is dependent on the actual values of the elements in the list. For descending order alone we need to pass something a little special to the method. We need to pass reverse **=** True to the sort() method for descending.

    myList = [1, 4, 8, 9, 3]
    myList.sort() 
    myList.sort(reverse = True)
    myList1 = ['a', 'z', 'y', 'e', 'b']
    myList1.sort()
    myList1.sort(reverse = True)

2: **reverse():**

As the name suggests, it is used to reverse the elements in the list but based on the index and not on the actual values.

    myList2 = [1, 3, 2, 5, 6]
    myList2.reverse()

3: **extend():**

Using the extend() method we can combine two lists just like we did with + operator we discussed earlier.

    myList = [1, 2, 3]
    myList2 = [4, 5]
    myList.extend(myList2)

This method updates the list we were applying it to show the concatenation of the two original lists.

4: **index():**

This method searches for the element we pass to it from the start of the list and returns its index. If the given element isn’t present it throws an error.

    myList = [1, 2, 3]
    index = myList.index(3)
    print(index)
    # index2 = myList.index(4)
    # The above line will throw an error

{% replit @Gothamv/lists4 %}

In this post we learned about the List Data Type, how to declare it, add lists together, indexing, slicing and it’s madness. We learnt some useful methods that we can apply on Lists as well. We can also have lists inside a list, even dictionaries, sets and tuples. We’ll learn more about them in a later post.

### And that’s pretty much it for the List Data Type in Python. What? I’m serious. This is all you need to know about Lists. For Now.

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

Next up: It's all about sets.