Python List and Functions (Methods/Operations)

0
258
python list functions methods operations

In this section we will discuss Python List and Functions.

Python list is denoted with the square brackets: []

So to create a list you have to put items inside a square brackets.

For example:

Input:

mylist = [1,2,3,4,5]

type(mylist)

Output:

list

Python list are allowed to contain different various types, unlike other programming language such as R (vectors).

So you can have a mix of variable types in one string. For example float, integer, boolean and string at the same time:

mylist2= [1,3.0,False,'text']

You can also have a list within a list.

mylist3= [1,2,3,4,5,['a','b','c']]

PYTHON LIST AND FUNCTIONS (METHODS/OPERATIONS)

  • Adding items to the list

To add an item to an existing list. Use .append to permanently add to a list.

For an existing list mylist = [1,2,3,4,5]

Input: mylist.append(6)

print(mylist)

Output:mylist = [1,2,3,4,5,6]

You can also do list concatenation when adding items.

For an existing list mylist = [1,2,3,4,5]

Input: mylist + [6]

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

Remember that for strings you must use quotations ' ' or " "

  • Removing items from a list 

.pop() function is used to remove an item from a list. By default it removes the last item from the list permanently.

mylist = [1,2,3,4,5]

Input: mylist.pop()

Output:5

Input: print(mylist)

Output: [1,2,3,4]

The specific item in the list can also be removed by using indexing (discussed in another article). Let’s remove the third element.

mylist = [1,2,3,4,5]

Input: mylist.pop(2)

Output:3

Input: print(mylist)

Output: [1,2,4,5]

  • Counting the number of items in a list

To know how many items there are in a list use len()

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

Input: len(mylist)

Output: 6

If you want to count specific values in a list use .count()

Input : mylist2= ['dog', 'cat', 'bear', 'dog']

mylist2.count('dog')

Output: 2

  • Rearranging the list order

If you want to sort the list use .sort()

Input: mylist3= [2,1,4,3,5]

mylist3.sort()

print(mylist3)

Output:

[1, 2, 3, 4, 5]

One important thing when working with list is indexing and slicing. See the link below

http://www.thedatalife.com/python-list-slicing-indexing/

To see the official Ptyhon documentation on list and methods. See the link below:

https://docs.python.org/3/tutorial/datastructures.html

LEAVE A REPLY

Please enter your comment!
Please enter your name here