Sunday, 23 January 2022

Python Lists and methods

 

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.


Ordered

When we say that lists are ordered, it means that the items have a defined order, and that order will not change.

If you add new items to a list, the new items will be placed at the end of the list.

Python Collections (Arrays)

There are four collection data types in the Python programming language:

  • List is a collection which is ordered and changeable. Allows duplicate members.
  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
  • Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.
  • Dictionary is a collection which is ordered** and changeable. No duplicate members.


Python has a set of built-in methods that you can use on lists.

MethodDescription
append()Adds an element at the end of the list
clear()Removes all the elements from the list
copy()Returns a copy of the list
count()Returns the number of elements with the specified value
extend()Add the elements of a list (or any iterable), to the end of the current list
index()Returns the index of the first element with the specified value
insert()Adds an element at the specified position
pop()Removes the element at the specified position
remove()Removes the item with the specified value
reverse()Reverses the order of the list
sort()Sorts the list

*Set items are unchangeable, but you can remove and/or add items whenever you like.

**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.


The list() Constructor

It is also possible to use the list() constructor when creating a new list.

Example

Using the list() constructor to make a List:

thislist = list(("apple""banana""cherry")) # note the double round-brackets
print(thislist)

If you insert more items than you replace, the new items will be inserted where you specified, and the remaining items will move accordingly:

Example

Change the second value by replacing it with two new values:

thislist = ["apple""banana""cherry"]
thislist[1:2] = ["blackcurrant""watermelon"]
print(thislist)

Result: thislist = ["apple", "blackcurrant", "watermelon", "cherry"]

Del

The del keyword also removes the specified index:

Example

Remove the first item:

thislist = ["apple""banana""cherry"]
del thislist[0]
print(thislist)
Try it Yourself »

The del keyword can also delete the list completely.

Example

Delete the entire list:

thislist = ["apple""banana""cherry"]
del thislist 
Try it Yourself »


Looping Using List Comprehension

List Comprehension offers the shortest syntax for looping through lists:

Example

A short hand for loop that will print all items in a list:

thislist = ["apple""banana""cherry"]
[print(x) for x in thislist] 
Try it Yourself »

List Comprehension

List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.

Example:

Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.

Without list comprehension you will have to write a for statement with a conditional test inside:

Example

fruits = ["apple""banana""cherry""kiwi""mango"]
newlist = []

for x in fruits:
  if "a" in x:
    newlist.append(x)

print(newlist) 
Try it Yourself »

With list comprehension you can do all that with only one line of code:

Example

fruits = ["apple""banana""cherry""kiwi""mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist) 
Try it Yourself »


The Syntax

newlist = [expression for item in iterable if condition == True]

The return value is a new list, leaving the old list unchanged.


Condition

The condition is like a filter that only accepts the items that valuate to True.

Example

Only accept items that are not "apple":

newlist = [x for x in fruits if x != "apple"
Try it Yourself »

The condition if x != "apple"  will return True for all elements other than "apple", making the new list contain all fruits except "apple".

The condition is optional and can be omitted:

Example

With no if statement:

newlist = [x for x in fruits] 
Try it Yourself »




No comments:

Post a Comment