All you need to know about Python Lists

kedark

Kedar Kodgire

Posted on April 1, 2020

All you need to know about Python Lists

What's a list?

It's one of the data structures in python. The lists are flexible and very easy to work with as they are mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item.


Creating a List

A list is created by placing all the items (elements) inside a square bracket [ ], separated by commas. It can also be created with list() function.

It can have any number of items and they may be of different types (integer, float, string, etc.). YOu can also have lists inside lists i.e. nested lists.

# empty list
new_list = []

# another way
another_list = list()

# list of integers
integer_list = [1, 2, 3]

# list with mixed datatypes
mixed_list = [1, "Hello", 3.4]

# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
Enter fullscreen mode Exit fullscreen mode

Accessing elements from the list

We can use [] to access an item in a list. The index starts from 0. So, a list having 5 elements will have an index from 0 to 4. The index must be an integer. We can't use float or other types, this will result in TypeError. Trying to access an element other that this will raise an IndexError.

>>> y = ['d', 'f', 's', 'd', 'f', 's', 'd', 'f']

>>> y[0]
'd'

# Nested List
>>> n_list = ["Happy", [2,0,1,5]]

>>> n_list[0][1]
'a'    

>>> n_list[1][3]
5
Enter fullscreen mode Exit fullscreen mode

Negetive Indexing

Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.

>>> y = ['d', 'f', 's', 'd', 'f', 's', 'd', 'f']
>>> y[-1]
'f'
Enter fullscreen mode Exit fullscreen mode

slicing in Lists

This is one of the interesting and easy ways of accessing a range of items in a list by using the slicing operator (colon). Let's look at some examples

>>> y = ['d', 'f', 's', 'd', 'f', 's', 'd', 'f']

>>> y[2:5]
['s', 'd', 'f']

>>> y[:] #getting complete list
['d', 'f', 's', 'd', 'f', 's', 'd', 'f']

>>> y[4:] #index 4 to end
['f', 's', 'd', 'f']

>>> y[:4] # from beginning to index 3
['d', 'f', 's', 'd']

>>> y[:-5]
['d', 'f', 's']
Enter fullscreen mode Exit fullscreen mode

Removing elements from the list

We can use the del keyword to remove an item at the given index.

the clear() method can also be used to empty a list.
let's look at some examples

>>> y = ['d', 'f', 's', 'd', 'f', 's', 'd', 'f']

>>> del y[0]

>>> y
['f', 's', 'd', 'f', 's', 'd', 'f']

>>> del y[1:3] #deleting multiple items

>>> del y # deleting list
Enter fullscreen mode Exit fullscreen mode

Adding or changing list items

We can use the assignment operator (=) to change an item or a range of items.

>>> y = ['d', 'f', 's', 'd', 'f', 's', 'd', 'f']

>>> y[0] = 'd'

>>> y
['d', 's', 'd', 'f', 's', 'd', 'f']
Enter fullscreen mode Exit fullscreen mode

We can use + operator to join two lists, * repeating list for a given number of times and we can insert one item at a desired location by using the method insert() or insert multiple items by squeezing it into an empty slice of a list.

>>>odd = [1, 3, 5]

>>> odd + [9, 7, 5]
[1, 3, 5, 9, 7, 5]

>>> ["list"] * 3
["list", "list", "list"]

>>>odd.insert(1,4)

>>> odd
[1, 4, 3, 5]

Enter fullscreen mode Exit fullscreen mode

List Comprehension

List comprehension is an elegant and concise way to create a new list from an existing list in Python. List comprehension consists of an expression followed by for statement inside square brackets.

Let's look at an example where we need to triple value of each element in the list

>>> [3 ** x for x in range(10)]
[1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683]
Enter fullscreen mode Exit fullscreen mode

This is equivalent to

three = []
for x in range(10):
   three.append(3 ** x)
Enter fullscreen mode Exit fullscreen mode

we can also use multiple for loops in it.


List methods

  • copy()

The copy method returns a shallow copy of the list. We can also copy one list into another like this

>>> y = ['d', 'f', 's', 'd', 'f', 's', 'd', 'f']

>>> x = y

>>> x
['d', 'f', 's', 'd', 'f', 's', 'd', 'f']
Enter fullscreen mode Exit fullscreen mode

The problem with this way of copying list is if you modify one list then another will also get modified. Hence, in this case, we use copy.

>>> list = ['cat', 0, 6.7]

>>> new_list = list.copy()

>>> new_list.append('dog')

>>> list
['cat', 0, 6.7]

>>> new_list
['cat', 0, 6.7, 'dog']
Enter fullscreen mode Exit fullscreen mode

  • remove()

The remove() method removes the first matching element (which is passed as an argument) from the list.

It takes a single element as an argument and removes it from the list. If the element doesn't exist, it throws ValueError: list.remove(x): x not in list exception. Let's look at an example.

>>> animals = ['cat', 'dog', 'rabbit', 'guinea pig']

>>> animals.remove('rabbit')

>>> animals
['cat', 'dog', 'guinea pig']

>>> animals = ['cat', 'dog', 'rabbit', 'rabbit', 'guinea pig']

>>> animals.remove('rabbit')

>>> animals
['cat', 'dog', 'rabbit', 'guinea pig']
Enter fullscreen mode Exit fullscreen mode

  • append()

The append() method adds a single item to the end of the list. The item can be numbers, strings, dictionaries, another list, and so on.

>>> animals = ['cat', 'dog', 'rabbit']

>>> wild_animals = ['tiger', 'fox']

>>> animals.append(wild_animals)

>>> animals
 ['cat', 'dog', 'rabbit', ['tiger', 'fox']]
Enter fullscreen mode Exit fullscreen mode

  • extend()

The extend() extends the list by adding all items of a list (passed as an argument) to the end.

>>> animals = ['cat', 'dog', 'rabbit']

>>> wild_animals = ['tiger', 'fox']

>>> animals.extend(wild_animals)

>>> animals
 ['cat', 'dog', 'rabbit', 'tiger', 'fox']
Enter fullscreen mode Exit fullscreen mode

similarly, If you need to add elements of other data types (like tuple and set) to the list, you can simply use:
list.extend(list(tuple_type))


  • count()

The count() method returns the number of times the element in the specified list. Let's have a look at an example

>>> nums = [1, 4, 2, 9, 7, 8, 9, 3, 1]

>>> x = nums.count(9)

>>> x
2
Enter fullscreen mode Exit fullscreen mode

  • index()

The index() method searches an element in the list and returns its index. If the same element is present more than once, the method returns the index of the first occurrence of the element.

>>> vowels = ['a', 'e', 'i', 'o', 'i', 'u']

>>> index = vowels.index('e')

>>> index
1
Enter fullscreen mode Exit fullscreen mode

  • len()

The len() function returns the number of items (length) in an object. An object can be (string, bytes, tuple, list, or range) or a collection (dictionary, set or frozen set)

>>> testString = 'Python'

>>> len(testString)
6

>>> vowels = ['a', 'e', 'i', 'o', 'i', 'u']

>>> len(vowels)
6
Enter fullscreen mode Exit fullscreen mode

  • pop()

The pop() method removes the item at the given index from the list and returns the removed item. The argument passed to the method is optional. If not passed, the default index -1 is passed as an argument (index of the last item). This helps us implement lists as stacks (first in, last out data structure).

>>> languages = ['Python', 'Java', 'C++', 'French', 'C']

>>> languages.pop(3)
'French'

>>> languages
['Python', 'Java', 'C++', 'C']
Enter fullscreen mode Exit fullscreen mode

  • clear()

The clear() method removes all items from the list. Note that the clear() method only empties the given list. It doesn't return any value.

>>> list = [{1, 2}, ('a'), ['1.1', '2.2']]

>>> list.clear()

>>> list
[]
Enter fullscreen mode Exit fullscreen mode

  • sort()

The sort() method sorts the elements of a given list in a specific order - Ascending or Descending.

By default, sort() doesn't require any extra parameters. However, it has two optional parameters:

  1. reverse - If true, the sorted list is reversed (or sorted in Descending order)
  2. key - function that serves as a key for the sort comparison

The syntax is

list.sort(key=..., reverse=...)

>>> vowels = ['e', 'a', 'u', 'o', 'i']

>>> vowels.sort()

>>> vowels
['a', 'e', 'i', 'o', 'u']

>>> vowels.sort(reverse=True)

>>> vowels
['u', 'o', 'i', 'e', 'a']
Enter fullscreen mode Exit fullscreen mode

Let's have a look at key now

>>> def takeSecond(elem):   
        return elem[1]

>>> random = [(2, 2), (3, 4), (4, 1), (1, 3)]

>>> random.sort(key=takeSecond)

>>> random
[(4, 1), (2, 2), (1, 3), (3, 4)]
Enter fullscreen mode Exit fullscreen mode

I hope you understood this. You can also use the sorted() function, it sorts the elements of a given iterable in a specific order (either ascending or descending).

The syntax of sorted() is:

sorted(iterable, key=None, reverse=False)
iterable is a sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any other iterator.


  • reverse()

The reverse() method reverses the elements of a given list. The reverse() function doesn't return any value. It only reverses the elements and updates the list.

>>> random = [(2, 2), (3, 4), (4, 1), (1, 3)]

>>> random.reverse()

>>> random
[(1, 3), (4, 1), (3, 4), (2, 2)]
Enter fullscreen mode Exit fullscreen mode

  • any()

The any() method returns True if any element of an iterable is True. If not, any() returns False. The any() method takes an iterable (list, string, dictionary etc.) in Python.

When Return Value
All values are true True
All values are false False
One value is true (others are false) True
One value is false (others are true) True
Empty Iterable False

Check out the examples below

>>> l = [1, 3, 4, 0]

>>> any(l)
True

>>> l = [0, False]

>>> any(l)
False

>>> l = [0, False, 5]

>>> any(l)
True

>>> l = []

>>> any(l)
False
Enter fullscreen mode Exit fullscreen mode

with strings

>>> s = '000'

>>> any(s)
True

>>> s = ''

>>> any(s)
False
Enter fullscreen mode Exit fullscreen mode

  • iter()

The Python iter() function returns an iterator for the given object. It creates an object which can be iterated one element at a time. These objects are useful when coupled with loops like for loop, while loop.

The syntax of the iter() function is:

iter(object, sentinel)

The iter() function takes two parameters:

  1. object - object whose iterator has to be created (can be sets, tuples, etc.)
  2. sentinel (optional) - value used to represent the end of the sequence.

Let's quickly look at the example

>>> x = iter(["apple", "banana", "cherry"])

>>> next(x)
'apple'

>>> next(x)
'banana'

>>> next(x)
'cherry'
Enter fullscreen mode Exit fullscreen mode

The sentinel is used very rarely, You can find more about it here


  • sum()

The sum() function adds the items of an iterable and returns the sum. The sum() function adds start and items of the given iterable from left to right.

It has two parameters

  1. iterable - iterable (list, tuple, etc). The items of the iterable should be numbers.
  2. start (optional) - this value is added to the sum of items of the iterable. The default value of start is 0 (if omitted)
>>> numbers = [1,2,3,4,5,1,4,5]

>>> sum(numbers)
25

>>> sum(numbers,25)
50
Enter fullscreen mode Exit fullscreen mode

  • abs()

The abs() method returns the absolute value of the given number. If the number is a complex number, abs() returns its magnitude.

  1. For integers - integer absolute value is returned
  2. For floating numbers - floating absolute value is returned
  3. For complex numbers - the magnitude of the number is returned

let's look at some examples

>>> integer = -20

>>> abs(integer)
20

>>> floating = -30.33

>>> abs(floating)
30.33

>>> complex = (3 - 4j)

>>> abs(complex)
5.0
Enter fullscreen mode Exit fullscreen mode

enumerate()

The enumerate() method adds a count to an iterable (lists, etc) and returns it. enumerate() has two parameters

  1. iterable - a sequence, an iterator, or objects that supports iteration
  2. start (optional) - enumerate() starts counting from this number. If start is omitted, 0 is taken as start.

Let's see a quick example

>>> numbers = [1,2,3,4,5,1,4,5]

>>> a = enumerate(numbers)

>>> print(list(a))
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 1), (6, 4), (7, 5)]

>>> a = enumerate(numbers, 50)

>>> print(list(a))
[(50, 1), (51, 2), (52, 3), (53, 4), (54, 5), (55, 1), (56, 4), (57, 5)]
Enter fullscreen mode Exit fullscreen mode

That's all folks, hope this added a little bit of value to your existing knowledge base.


other reads


Keep in Touch

Don't forget to connect me on:

Have a great day,
Happy Learning,
and stay safe.

💖 💪 🙅 🚩
kedark
Kedar Kodgire

Posted on April 1, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related