Lists

--Originally published at Hector Martinez Alcantara

In this posst we’re going to explain some things about the lists in python.

Firstly, a list is like an array of diferent or equal type of elements which can be updated, enlarged and shortened.

The syntax of a list is the next:

List= ["element 1", 2,"element3",...,n]

To access a list you have to type brackets after the list name, and between them the number of the position you want to acess.

print(List[0]); #This shows'element 1' which is the first element of List
print(List[1:3]) #This prints the elements in position 1 to position 3

To update an element of  the list you only have to assign the new value to the List’s position.

List[0]="New element"

To delete an element you have to use the function del with the position of the list that you want to delete.

del(List[4])

Then there are some operations with operators that are basic in a list like: +, *, len, in, for.

Python Expression Results Description
len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
[‘Hi!’] * 4 [‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’] Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: print x, 1 2 3 Iteration

 

Python Expression Results Description
L[2] ‘SPAM!’ Offsets start at zero
L[-2] ‘Spam’ Negative: count from the right
L[1:] [‘Spam’, ‘SPAM!’] Slicing fetches sections

Some Basic  methods

cmp(list1, list2)
Compares elements of both lists.

len(list)
Gives the total length of the list.

max(list)
Returns item from the list with max value.

min(list)
Returns item from the list with min value.

list(seq)
Converts a tuple into list.
Python also includes following list methods

list.append(obj)
Appends object obj to list

list.count(obj)
Returns count of how many

obj occurs in list

list.extend(seq)
Appends the contents of seq to list

list.index(obj)
Returns the lowest index in list that obj appears

list.insert(index, obj)
Inserts object obj into list at offset index

list.pop(obj=list[-1])
Removes and returns last object or obj from list

list.remove(obj)
Removes object obj from list

list.reverse()
Reverses objects of list in place

list.sort([func])
Sorts objects of list, use compare func if given

Tables and methods used from Tutorialspoint.

And that’s the basic of the lists,thanks for reading and special thanks to Tutorialspoint who made an excelent post, it helps me a lot.