The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number - its position or index. The first index is zero, the second index is one,and so forth.
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.
Python has six built-in types of sequences, but the most common ones are lists and tuples,which we would see in this tutorial.
There are certain things you can do with all the sequence types. These operations include indexing, slicing, adding, multiplying, and checking for membership. In addition, Python has built-in functions for finding the length of a sequence and for finding its largest and smallest elements.
Python Lists
The list is the most versatile data type available in Python, which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that the items in a list need not be of the same type.
There are several ways to create a new list; the simplest is to enclose the elements in square brackets (“[" and “]”):
for example :-
[10, 20, 30, 40]
['string', 'list']
The first example is a list of four integers. The second is a list of two 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:
[ 'list', 2.0, 5, [10] ]
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:
Note : A mutable object can be changed after it is created, and an immutable object can't.
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:
>>> ls = ['zero', 'one', 'two']
>>> print(ls[0])
'zero'
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:
Python Expression | Result | Description |
---|---|---|
list[0] | 1 | Offsets start at zero |
list[-1] | 5 | Negative: count from the right |
list[0:] | 1,2,3,4,5 | Offsets start at zero |
• 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. It starts with -1.
>>> a = [1,2,3,4,5]
>>> print(a[-1]
5
>>> print(a[-2])
4
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 var in list:
print(var)
for example:-
Delete List Elements
Items of the list can be deleted using del statement by specifying the index of item (element) to be deleted.
syntax :
list = []
del list[index]
example:-
List operations
Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string.
In fact, lists respond to all of the general sequence operations we used on strings in the prior chapter.
Python Expression | Result | Description |
---|---|---|
len([1,2,3]) | 3 | Length |
[1,2] + [5,6] | [1,2,3,4] | Concatenation |
['H!'] * 3 | ['H!','H!','H!'] | Repetition |
3 in [1, 2, 3] | True | Membership |
for x in [1,2,3] :
print (x,end=' ') |
1 2 3 | Iteration |
list = [1,2,3,4,5]
List slices
Since lists are sequences, indexing and slicing work the same way for lists as they do for strings.
syntax:-
slice(start, end, step)
or
[start, end, step]
Parameter | Description |
---|---|
start | Optional. An integer number specifying at which position to start the slicing. Default is 0 |
end | An integer(n) number specifying at which position to end the slicing. end = n - 1 |
step | Optional. An integer number specifying the step of the slicing. Default is 1 |
>>> t = ['a','b','c',]
>>> t[1:3]
['b', 'c']
>>> t[:4]
['a', 'b', 'c']
>>> t[2:]
['c']
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']
>>> t[0:2] = ['x', 'y']
>>> print(t)
['x','y','c']
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.
Lists and strings
A string is a sequence of characters and a list is a sequence of values, but a list of characters is not the same as a string. To convert from a string to a list of characters, you can use list:
>>> s = 'List'
>>> t = list(s)
>>> print(t)
['L', 'i', 's', 't']
Because list is the name of a built-in function, you should avoid using it as
a variable name. I also avoid the letter “l” because it looks too much like the
number “1”. So that’s why I use “t” or "ls".
The list function breaks a string into individual letters. If you want to break a
string into words, you can use the split method:
>>> s = 'List by split'
>>> ls = s.split()
>>> print(ls)
['List', 'by', 'split']
>>> print(ls[2])
split
split
Once you have used split to break the string into a list of words, you can use the index operator (square bracket) to look at a particular word in the list.
You can call split with an optional argument called a delimiter that specifies
which characters to use as word boundaries. The following example uses a hyphen as a delimiter:
>>> str = 'first/second'
>>> delimiter = '/'
>>> str.split(delimiter)
['first', 'second']
join is the inverse of split. It takes a list of strings and concatenates the elements. join is a string method, so you have to invoke it on the delimiter and pass the list as a parameter
ls = ['str1', 'str2', 'str3','strN']
add = '+'
j = b.join(add)
print(j)
Objects and values
If we execute these assignment statements:
a = 'banana'
b = 'banana'
we know that a and b both refer to a string, but we don’t know whether they refer to the same string. There are two possible states:
a ====> 'banana'
b ====> 'banana'
or
a,b ==> 'banana'
Note : An object is simply a collection of data (variables), that store values and allocates memory location to store values.
In one case, a and b refer to two different objects that have the same value. In the second case, they refer to the same object.
To check whether two variables refer to the same object(variable), you can use the is operator.
>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True
In this example, Python only created one string object, and both a and b refer to it.
But when you create two lists, you get two objects(variables):
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False
In this case we would say that the two lists are equivalent, because they have the
same elements, but not identical, because they are not the same object. If two
objects are identical, they are also equivalent, but if they are equivalent, they are
not necessarily identical.
Until now, we have been using “object” and “value” interchangeably, but it is more
precise to say that an object has a value. If you execute a = [1,2,3], a refers to
a list object whose value is a particular sequence of elements. If another list has
the same elements, we would say it has the same value.
0 Comments