Lists - RaspPywriter/Python-Data-Structures GitHub Wiki

List Methods

Lists are a collection which is ordered and changeable.

list.append()

Append adds to a list

Append Example

fruits = ['apple', 'banana', 'cherry'] fruits.append("orange")

list.index()

The index method returns the first value found.

Index Example

index = fruits.index('cherry')

Accessing List Elements

fruits[1] --> 'banana'

Example 2 thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[2:5]) --> ['cherry', 'orange', 'kiwi']

Example 3 #This will return the items from index 0 to index 4. thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[:4])

Changes a list element

Changes banana to blackcurrant thislist = ["apple", "banana", "cherry"] thislist[1] = "blackcurrant"

Insert an Item into a List

Insert takes two parameters, and index (where to put the value) and the value itself. thislist.insert(2, "orange")

###list.extend()

Extending a list

Original language list language = ['French', 'English']

language list 2 language1 = ['Spanish', 'Portuguese']

appending language1 elements to language language.extend(language1)

Language List: ['French', 'English', 'Spanish', 'Portuguese']

list.remove()

Remove an item from a list

animals = ['cat', 'dog', 'rabbit', 'guinea pig']

animals.remove('rabbit')

list.sort()

Sort the items of the list in place alphabetically.

Examples

list.sort(reverse=True) --> reverse sort (descending order)

list.reverse()

Reverse the elements of the list in place.

list.copy()

Return a shallow copy of the list. Equivalent to a[:].