Skip to content

Latest commit

 

History

History
237 lines (173 loc) · 6.59 KB

4.lists.adoc

File metadata and controls

237 lines (173 loc) · 6.59 KB

Lists, Tuples and Dictionaries

Learning Material

Lists

Lists are sequences, ordered collections of objects separated by commas. They are declared with the indicating operator [].

myList = ["a","b","c", "d"]

A value can be accessed by indicating the index.

print(myList[0]) ## Output: a

We can also specify that we only want the first two elements of the list.

print(myList[:2]) ## Output: ['a','b']

If we want to reverse the list you can do it.

print(myList[::-1]) ## Output: ['d','c','b','a']

Warning, the indexes always start from 0. It’s a little disturbing at first, but you have to get used to it. Other examples of what can be done with the lists.

myList = myList * 5
print(myList)
## Output: ['a','b','c','a','b','c','a','b','c','a','b','c','a','b','c']

myList.append("Add Text")
print(myList)
## Output: ['a','b','c','a','b','c','a','b','c','a','b','c','a','b','c','Add Text']

You can put any type of data in it :

var = "Hello, i am a variable that contains String values"
otherList = [193.45, "Hello", ["Inception list", "Two elements"], 89, var]
print(otherList)

You can also merge two tables

x = [1, 2, 3, 4]
y = [4, 5, 1, 0]
x.extend(y)
print(x) ## Output: [1, 2, 3, 4, 4, 5, 1, 0]

# OR
x = [1, 2, 3, 4]
y = [4, 5, 1, 0]

xy = x + y
print(xy) ## Output: [1, 2, 3, 4, 4, 5, 1, 0]

There are many methods, I invite you to find them out by doing some research.

Tuples

Python offers a type of data called tuple (term meaning Table UPLEt), which is quite similar to a list but cannot be modified. Tuples are therefore preferable to lists whenever you want to be sure that the data transmitted is not modified by mistake within a program.

In addition, tuples are less greedy in terms of system resources (they take less memory space). Tuples are immutable objects (We will see what this means a little later).

tupleExample = ("Moriarty", "Sherlock", "Watson")
listExample = ["Moriarty", "Sherlock", "Watson"]

Tuples vs Lists

As we can see, when we try to modify the content of a Tuple object, we get an error. However, no problem for the list.

tupleExample.append("Lestrade")

## AttributeError: 'tuple' object has no attribute 'append'

listExample.append("Lestrade")
print(listExample)

And as we have seen previously, even if we save the listExample variable in another variable and make a modification on one of the lists, both lists will be impacted.

listExample2 = listExample
listExample2.append("Hudson")

print(listExample2)
print(listExample)

So if you need to process a collection that will not change, use tuples. On the other hand, if you know that this collection will have to be changed, then use the lists.

Dictionaries

The dictionaries or associative arrays are not a sequence but another composite type. They look similar to the lists to some extent (they are editable like them), but the elements we are going to record will not be arranged in an unchanging order. On the other hand, we will be able to access any of them using a specific index called a key, which can be alphabetical, numerical, or even a composite type under certain conditions. Note: Like in a list, the elements stored in a dictionary can be of any type (numerical values, strings, lists, etc.).

In dictionaries, indexes will be strings of characters, unlike lists.

Since the dictionary type is a modifiable type, we can start by creating an empty dictionary and then fill it in little by little. From a syntactic point of view, a dictionary-type data structure is recognized by the fact that its elements are enclosed in a pair of braces. An empty dictionary will therefore be noted {}

heroes = {}
heroes["Batman"] = "Bruce Wayne"
heroes["Superman"] = "Clark Kent"
print(heroes)

## Output: {'Batman': 'Bruce Wayne', 'Superman': 'Clark Kent'}

As you can see in the line above, a dictionary appears as a series of elements separated by commas (all enclosed between two braces). Each of these elements consists of a pair of objects: an index and a value, separated by a colon.

In a dictionary, indexes are called keys, so elements can be called key-value pairs. You may notice that the order in which the elements appear in the last line does not correspond to the order in which we provided them. This is absolutely irrelevant: we will never try to extract a value from a dictionary using a numerical index. Instead, we will use the keys:

print(heroes["Batman"]) ## Output: Bruce Wayne
print(heroes["Superman"]) ## Output: Clark Kent

Here, Batman and Superman are the keys and Bruce Wayne and Clark Kent are the values.

Unlike lists, it is not necessary to use a particular method to add new elements to a dictionary: simply create a new key-value pair.

heroes["Spiderman"] = "Peter Parker"
print(heroes)

## Output: {'Batman': 'Bruce Wayne', 'Superman': 'Clark Kent', 'Spiderman': 'Peter Parker'}

Exercises

1. Choose 5 movies you like and create a dictionary that associates each of these movies with its director.

2. Add an entry to the dictionary of the previous question (a new movie and its director)

3. How would you cut the following string at each space and put it in a list:

sentence = "I am the best coder in Telenet !"

4. Transform this string Why_am_I_Mister_pink_? by removing the underscores: Why am I Mister pink ?

5. Display only values of this dictionary.

movies = {"Memories of Murder" : "Bong Joon Ho", "Pulp Fiction" : "Quentin Tarantino", "The Usual Suspects" :"Bryan Singer"}

6. Display only keys of this dictionary.

movies = {"Memories of Murder" : "Bong Joon Ho", "Pulp Fiction" : "Quentin Tarantino", "The Usual Suspects" :"Bryan Singer"}

7. Replace the value of Pulp Fiction by Quentin Tarantino.

movies = {"Memories of Murder" : "Bong Joon Ho", "Pulp Fiction" : "That guy!", "The Usual Suspects" :"Bryan Singer"}

8. Create a dictionary to build the total time with the length of each movie corresponding to the following table:

Memories Of Murder // 132 minutes
Pulp Fiction // 154 minutes
The Usual Suspects // 106 minutes
Interstellar // 169 minutes
Take Shelter // 120 minutes

9. Calculate the number of hours it takes to watch all the movies

10. Remove one of the movies from the dictionary