Lists in python

Lists in python are a variable in which you can put several variables.

Lists in python

Lists in python are a variable in which you can put several variables.

How to create a list in python?

To create a list, it is very simpler:

>>> list = [] # an empty list

You can see the contents of the list by writing the following code :

>>> list

<type 'list'>

How to add a value to a python list?

You can add the values you want when creating the python list:

>>> list = [1,2,3]

>>> list

[1, 2, 3]

Or add them after creating the list with the append method

>>> list = []

>>> list

[]

>>> list.append(1)

>>> list

[1]

>>> list.append("ok")

>>> list

[1, 'ok']

As you can see it is possible to mix in one list, many variables with different type. We can even put a list in a list.

How to display an item from a list?

To view a list, you can directly access the index of the desired value

>>> list = ["a","d","m"]

>>> list[0]

'a'

>>> list[2]

'm'

Note that the first item always starts from the index 0. To read the first item we use the value 0, the second we use the value 1, etc.

It is also possible to modify a value using its index

 

>>> list = ["a","d","m"]

>>> list[0]

'a'

>>> list[2]

'm'

>>> list[2] = "z"

>>> list

['a', 'd', 'z']

How to delete an entry using its index?

Sometimes it is necessary to delete an entry from the list. To do this you can use the del function.

>>> list = ["a", "b", "c"]

>>> del list[1]

>>> list

['a', 'c']

How to delete an entry using its value?

It is possible to remove an entry from a list with its value using the remove method.

>>> list = ["a", "b", "c"]

>>> list.remove("a")

>>> list

['b', 'c]

Ho to reverse the order of values in a list ?

You can reverse the items of a list using the reverse method.

>>> list = ["a", "b", "c"]

>>> list.reverse()

>>> list

['c', 'b', 'a']

How to count the number of items in a list?

It is possible to count the number of items in a list using the len function.

>>> list = [1,2,3,5,10]

>>> len(list)

5

How to count the number of occurrences of a value?

To know the number of occurrences of a value in a list, you can use the count method.

 

How many times "a" or "c" are repeated in the list?

>>> list = ["a","a","a","b","c","c"]

>>> list.count("a")

3

>>> list.count("c")

2

How to find the index of a value ?


The index method allows you to know the position of the item

>>> list = ["a","a","a","b","c","c"]

>>> list.index("b")

3

Here are some tips for slicing lists

>>> list = [1, 10, 100, 250, 500]

>>> list[0]

1

>>> list[-1] # To print the last value

500

>>> list[-4:] # To print the last 4 values

[500, 250, 100, 10]

>>> list[:] # To print all the values

[1, 10, 100, 250, 500]

>>> list[2:4] = [69, 70]

[1, 10, 69, 70, 500]

>>> list[:] = [] # Empty the list!

[]

How to loop on a list?

To display the values of a list, you can use a loop:

>>> list = ["a","d","m"]

>>> for l in list: # l is the counter

...print l

...

a

d

m

 

If you want to retrieve the index, you can use the enumerate function.

>>> for l in enumerate(list):

...print l

...

(0, 'a')

(1, 'd')

(2, 'm')

The type of values returned by the loop is tuples! To learn more about tuples please read this.

See : Tuple in python

How to copy a list ?

Many beginners make the mistake and copy a list using this solution:

>>> x = [1,2,3]
>>> y = x

However, in this case, if you change a value of the list y, the list x will also be affected by this modification:

>>> x = [1,2,3]
>>> y = x
>>> y[0] = 4
>>> x
[4, 2, 3]

In fact, this syntax allows you to work on the same elements of the list x but with a different name y

So how do you copy a list independently?

>>> x = [1,2,3]

>>> y = x[:]

>>> y[0] = 9

>>> x

[1, 2, 3]

>>> y

[9, 2, 3]

For more complex data, you can use the deepcopy function of the copy module

>>> import copy

>>> x = [[1,2], 2]

>>> y = copy.deepcopy(x)

>>> y[1] = [1,2,3]

>>> x

[[1, 2], 2]

>>> y

[[1, 2], [1, 2, 3]]

How to convert string to list?

Sometimes it can be useful to convert a string into a list. This is possible using the split method.

>>> S = "welcom:walid:!"

>>> S.split(":") # Specifies the separator to use when splitting the string S. If you use split() then separator is the whitespace

['welcom', 'walid', '!']

How to convert a list to string?

it is possible using the "join" method.

>>> list = ["welcom","walid","!"]

>>> ":".join(list)

'welcom:walid:!'

How to find an item in a list?

To find out if an item is in a list or not, you can use this instruction:

>>> list = [1,2,3,5,10]

>>> 3 in list

True

>>> 11 in list

False

Range function

The range function generates a list made up of a simple arithmetic sequence.

>>> range(10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Expand a list with another list

To put two lists, you can use the extend method

>>> x = [1, 2, 3, 4]

>>> y = [4, 5, 1, 0]

>>> x.extend (y)

>>> print x

[1, 2, 3, 4, 4, 5, 1, 0]

Permutations

The permutation of a set of elements is a list of all possible cases. itertools does it for you:

>>> from itertools import permutations

>>> list (permutations (['a', 'b', 'c']))

[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c ',' a '), (' c ',' a ',' b '), (' c ',' b ',' a ')]

Swapping a list of lists

How to display all the possible cases of a list itself composed of list? With the product tool from itertools:

>>> from itertools import product

>>> list (product (['a', 'b'], ['c', 'd']))

[('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd')]

Tips

Display the first 2 elements of a list

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

>>> list [: 2]

[1, 2]

Display the last item in a list:

>>> list = [1, 2, 3, 4, 5, 6]

>>> list [-1]

6

Display the 3rd element from the end:

>>> list = [1, 2, 3, 4, 5, 6]

>>> list [-3]

4

Display the last 3 elements of a list:

>>> list = [1, 2, 3, 4, 5, 6]

>>> list [-3:]

[4, 5, 6]

You can concatenate two lists to combine them together using the + operator:

>>> x = [1, 2, 3]

>>> y = [4, 5, 6]

>>> x + y

[1, 2, 3, 4, 5, 6]

You can even multiply a list:

>>> x = [1, 2]

>>> x * 5

[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]

This can be useful to initialize a list, for example a list of 5 elements:

>>> [0] * 5

[0, 0, 0, 0, 0]

What's Your Reaction?

like
0
dislike
0
love
0
funny
0
angry
0
sad
0
wow
0