List, Tuple and Dictionary in Python

 Lists

 A list is a sequence

List Items

List items are ordered, changeable, and allow duplicate values.

List items are indexed, the first item has index [0], the second item has index [1] etc.

List Length

To determine how many items a list has, use the len() function:

Example

Print the number of items in the list:

thislist = ["apple""banana""cherry"]
print(len(thislist))
Like a string, a list is a sequence of values. In a string, the values are characters;
in a list, they can be any type. The values in list are called
elements or sometimes
items. There are several ways to create a new list; the simplest is to enclose the elements in square brackets (“[" and “]”):
[10, 20, 30, 40]
[
'crunchy frog', 'ram bladder', 'lark vomit']
The first example is a list of four integers. The second is a list of three strings.
The elements of a list don’t have to be the same type. The following list contains
a string, a float, an integer, and (lo!) another list:
['spam', 2.0, 5, [10, 20]]
A list within another list is nested.
A list that contains no elements is called an empty list; you can create one with
empty brackets,
[].
As you might expect, you can assign list values to variables:
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> numbers = [17, 123]
>>> empty = []
>>> print(cheeses, numbers, empty)
[
'Cheddar', 'Edam', 'Gouda'] [17, 123] []


Lists are mutable
The syntax for accessing the elements of a list is the same as for accessing the
characters of a string: the bracket operator. The expression inside the brackets
specifies the index. Remember that the indices start at 0:
>>> print(cheeses[0])
Cheddar
Unlike strings, lists are mutable because you can change the order of items in a
list or reassign an item in a list. When the bracket operator appears on the left
side of an assignment, it identifies the element of the list that will be assigned.
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print(numbers)
[
17, 5]
The one-th element of numbers, which used to be 123, is now 5.
You can think of a list as a relationship between indices and elements. This relationship is called a
mapping; each index “maps to” one of the elements.
List indices work the same way as string indices:
• Any integer expression can be used as an index.
• If you try to read or write an element that does not exist, you get an
IndexError.
• If an index has a negative value, it counts backward from the end of the list.
The
in operator also works on lists.
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False

Traversing a list
   The most common way to traverse the elements of a list is with a for loop. The
syntax is the same as for strings:
for cheese in cheeses:
     print(cheese)
or you can simply traverse a list in printing it like this:
>>>print(*cheeses)

This works well if you only need to read the elements of the list. But if you want
to write or update the elements, you need the indices. A common way to do that
is to combine the functions
range and len:
for i in range(len(numbers)):
numbers[i]
= numbers[i] * 2
This loop traverses the list and updates each element. len returns the number of
elements in the list.
range returns a list of indices from 0 to n - 1, where n is
the length of the list. Each time through the loop,
i gets the index of the next
element. The assignment statement in the body uses
i to read the old value of the
element and to assign the new value.
A
for loop over an empty list never executes the body:
for x in empty:
print(
'This never happens.')
Although a list can contain another list, the nested list still counts as a single
element. The length of this list is four:
['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]

List Operations
The + operator concatenates lists:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print(c)
[
1, 2, 3, 4, 5, 6]
Similarly, the * operator repeats a list a given number of times:
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
The first example repeats four times. The second example repeats the list three
times.


List slices
The slice operator also works on lists:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3]
[
'b', 'c']
>>> t[:4]
[
'a', 'b', 'c', 'd']
>>> t[3:]
[
'd', 'e', 'f']
If you omit the first index, the slice starts at the beginning. If you omit the second,
the slice goes to the end. So if you omit both, the slice is a copy of the whole list.
>>> t[:]
[
'a', 'b', 'c', 'd', 'e', 'f']
Since lists are mutable, it is often useful to make a copy before performing operations that fold, spindle, or mutilate lists.
A slice operator on the left side of an assignment can update multiple elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> print(t)
[
'a', 'x', 'y', 'd', 'e', 'f']

List methods

Python provides methods that operate on lists. For example, append adds a new
element to the end of a list:
>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> print(t)
[
'a', 'b', 'c', 'd']
extend
takes a list as an argument and appends all of the elements:
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> print(t1)
[
'a', 'b', 'c', 'd', 'e']
This example leaves t2 unmodified.
sort arranges the elements of the list from low to high:
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> print(t)
[
'a', 'b', 'c', 'd', 'e']
Most list methods are void; they modify the list and return None. If you accidentally write t = t.sort(), you will be disappointed with the result.

Deleting elements
There are several ways to delete elements from a list. If you know the index of the
element you want, you can use
pop:
>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> print(t)
[
'a', 'c']
>>> print(x)
b
pop
modifies the list and returns the element that was removed. If you don’t
provide an index, it deletes and returns the last element.
If you don’t need the removed value, you can use the
del operator:
>>> t = ['a', 'b', 'c']
>>> del t[1]
>>> print(t)
[
'a', 'c']
If you know the element you want to remove (but not the index), you can use
remove:
>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> print(t)
[
'a', 'c']
The return value from remove is None.
To remove more than one element, you can use
del with a slice index:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> print(t)
[
'a', 'f']
As usual, the slice selects all the elements up to, but not including, the second
index.


Lists and functions
There are a number of built-in functions that can be used on lists that allow you
to quickly look through a list without writing your own loops:
>>> nums = [3, 41, 12, 9, 74, 15]
>>> print(len(nums))
6
>>> print(max(nums))
74
>>> print(min(nums))
3
>>> print(sum(nums))
154
>>> print(sum(nums)/len(nums))
25
The sum() function only works when the list elements are numbers. The other
functions (
max(), len(), etc.) work with lists of strings and other types that can
be comparable.


Dictionaries

A dictionary is like a list, but more general. In a list, the index positions have to
be integers; in a dictionary, the indices can be (almost) any type.
You can think of a dictionary as a mapping between a set of indices (which are
called
keys) and a set of values. Each key maps to a value. The association of a
key and a value is called a
key-value pair or sometimes an item.
As an example, we’ll build a dictionary that maps from English to Spanish words,
so the keys and the values are all strings.
The function
dict creates a new dictionary with no items. Because dict is the
name of a built-in function, you should avoid using it as a variable name.
>>> eng2sp = dict()
>>> print(eng2sp)
{}
The curly brackets, {}, represent an empty dictionary. To add items to the dictionary, you can use square brackets:
>>> eng2sp['one'] = 'uno'
This line creates an item that maps from the key 'one' to the value “uno”. If we
print the dictionary again, we see a key-value pair with a colon between the key
and value:
>>> print(eng2sp)
{
'one': 'uno'}
This output format is also an input format. For example, you can create a new
dictionary with three items. But if you print
eng2sp, you might be surprised:
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
>>> print(eng2sp)
{
'one': 'uno', 'three': 'tres', 'two': 'dos'}

Tuples

mytuple = ("apple""banana""cherry")

Tuple

Tuples are used to store multiple items in a single variable.

Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are ListSet, and Dictionary, all with different qualities and usage.

A tuple is a collection which is ordered and unchangeable.

Tuples are written with round brackets.

Example

Create a Tuple:

thistuple = ("apple""banana""cherry")
print(thistuple)
Tuples are immutable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.
A tuple1 is a sequence of values much like a list. The values stored in a tuple can
be any type, and they are indexed by integers. The important difference is that
tuples are
immutable. Tuples are also comparable and hashable so we can sort lists
of them and use tuples as key values in Python dictionaries.
Syntactically, a tuple is a comma-separated list of values:
>>> t = 'a', 'b', 'c', 'd', 'e'
Although it is not necessary, it is common to enclose tuples in parentheses to help
us quickly identify tuples when we look at Python code:
>>> t = ('a', 'b', 'c', 'd', 'e')
To create a tuple with a single element, you have to include the final comma:
>>> t1 = ('a',)
>>> type(t1)
<type 'tuple'>
Without the comma Python treats ('a') as an expression with a string in parentheses that evaluates to a string:
>>> t2 = ('a')
>>> type(t2)
<type 'str'>
Another way to construct a tuple is the built-in function tuple. With no argument,
it creates an empty tuple:

>>> t = tuple()
>>> print(t)
()
If the argument is a sequence (string, list, or tuple), the result of the call to tuple
is a tuple with the elements of the sequence:
>>> t = tuple('lupins')
>>> print(t)
(
'l', 'u', 'p', 'i', 'n', 's')
Because tuple is the name of a constructor, you should avoid using it as a variable
name.
Most list operators also work on tuples. The bracket operator indexes an element:
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print(t[0])
'a'
And the slice operator selects a range of elements.
>>> print(t[1:3])
(
'b', 'c')
But if you try to modify one of the elements of the tuple, you get an error:
>>> t[0] = 'A'
TypeError: object doesn't support item assignment
You can’t modify the elements of a tuple, but you can replace one tuple with
another:
>>> t = ('A',) + t[1:]
>>> print(t)
(
'A', 'b', 'c', 'd', 'e')

Comments

Post a Comment

Popular posts from this blog

HISTOIRE DE MINEMBWE ET SES AUTOCHTONES

Variables, expressions, and statements in Python

Extracting Dates From Medical Data