LISTS



Skip to a subsection :

  1. DIVE INTO THE LISTS
  2. WORKING WITH LISTS
  3. METHODS
  4. LIST COMPREHENSIONS
  5. CODE SNIPPETS




1. DIVE INTO THE LISTS

Ordered

A list is an ordered collection of items, meaning that each item has a fixed position in the list.

Mutable

A list is mutable, meaning that you can change its contents by adding, modifying, or removing items.

Duplicates

Lists allow duplicates, which means you can have multiple copies of the same item in a single list.

Syntax

Lists are defined using square brackets [ ] and the items are separated by commas.

Item types

The items in a list can be of different types, such as integers, floats, strings, or even other lists.

Utilizing lists

Lists are particularly useful when you need to change the items in the list or add new items. The choice between a list and a tuple will often depend on whether you need to change the items in the collection or store data that should not be modified.


2. WORKING WITH LISTS

It is generally a good practice to store data objects like lists in variables because it allows you to manipulate the list more easily and conveniently. Here is how you can create lists.

# example 1 : a list of integers
list1 = [5, 8, 8, 7, 3 ]
# example 2 : a list of strings
list2 = ['a', 'e', 'i', 'o', 'u']
# example 3 : another list of strings
list3=['car', 'bag', 'shirt', 'bed', 'fork', 'cup', 'spoon']
# example 4 : a list of strings and integers
list4=[5,2,'r','r',10,'t']
# example 5 : a list of lists
list5=[list1,list2]
print(list5) # prints ((5, 8, 8, 7, 3), ('a', 'e', 'i', 'o', 'u'))
#example 6 : a list of floats
list6=[1.5,2.2,3.9]
#example 7 : an empty list
emptylist=[]

Each item has a specific position or index. You can access the elements of list using their index within square brackets []. In python, indexing of sequences starts at 0. This means that the first element in a sequence is at index 0, the second element is at index 1. This is a common convention in programming languages. Indexing stops at the right limit of the indexes passed as arguments ( exclusive )

animals=["cat", "dog", "bird", "fish", "rabbit"]
print(animals[1]) # prints dog
print(animals[0]) # prints cat
print(animals[1:3]) # prints ['dog', 'bird']

Lists allow duplicates :

colors=['blue','red','blue','green']
print(colors) #prints ['blue', 'red', 'blue', 'green']

Common opertors :

list1 = ['a']
list2 = ['2']
print(list1 + list2)  # prints ['a', '2']
print(list1 * 3)  # prints ['a', 'a', 'a']
print('a' in list1)  # prints True
print('b' in list1)  # prints False
print('a' not in list1)  # prints False
print(list1[0])  # prints 'a'


3. METHODS

A method is a function that is associated with a specific object or class and performs a specific task. The methods for working with dictionaries can be categorized into the following groups:

These categories are not official and there are other ways to categorize the methods. The goal of these categories is to provide a helpful overview and a way to better understand and organize the many tools available.


ACCESS METHODS

count() : returns the number of times a value appear in the list :

colors=['blue','red','blue','green']
print(colors.count('blue')) # prints 2

index(): returns the first index of value.

colors=['yellow','blue','red','blue','green']
print(colors.index('blue')) #prints 1

to limit the search to a particular sequence of the list :

towns=['London', 'Sydney', 'Roma', 'Sydney', 'Paris' ]
print(towns.index('Sydney', 1, 2)) # prints 1
print(towns.index('Sydney', 2, 4)) # prints 3

SORTING METHODS

sort() : sorts lists

animals=["cat", "dog", "bird"]
numbers=[7,10,2,20]
animals.sort()
numbers.sort()
print(animals) # prints ['bird', 'cat', 'dog']
print(numbers) # prints [2, 7, 10, 20]

If you try to sort a list that contains both strings and numbers, you will get a TypeError with the message "'<' not supported between instances of 'int' and 'str'". This error occurs because the sort() method does not know how to compare elements of different types, and therefore cannot determine the correct order in which to place them.

aList=['monday',10,2,'thursday']
aList.sort() # returns TypeError: '<' not supported between instances of 'int' and 'str' ''>''

reverse() : reverses the list

colors=['yellow','blue','red','blue','green']
colors.reverse()
print(colors) # prints ['green', 'blue', 'red', 'blue', 'yellow']

ADDING METHODS

append() : appends object to the end of the list

animals=["cat", "dog", "bird"]
animals.append('turtle')
print(animals) # prints ['cat', 'dog', 'bird', 'turtle']

insert() : inserts an element at a specific position in a list

animals=["cat", "dog", "bird"]
animals.insert(2,'turtle')
print(animals) # prints ['cat', 'dog', 'turtle', 'bird']

extend() : extends list by appending elements from the iterable. Lists are iterables, we can extend a list by appending elements from another list :

days=['Monday','Tuesday']
animals=['cat','dog']
days.extend(animals)
print(days) # prints ['Monday', 'Tuesday', 'cat', 'dog']

REMOVING METHODS

clear() : removes all items from list

animals=["cat", "dog", "bird"]
animals.clear()
print(animals) # prints []

pop() : removes and returns an item at a given index

colors=['yellow','blue','red','blue']
colors.pop(2)
print(colors) # prints ['yellow', 'blue', 'blue']

if the index is not specified in the pop() method, it removes the last item of the list

sports=['tennis', 'basketball', 'cricket']
sports.pop()
print(sports) # prints ['tennis', 'basketball']

remove() : removes the first occurence of the value

colors=['yellow','blue','green','blue']
colors.remove('blue')
print(colors) # prints ['yellow', 'green', 'blue',]

OTHER METHODS

copy(): returns a shallow copy of a list.

cities1=['Sydney','Tokyo','Madrid']
cities2=cities1.copy()
print(cities2) # prints ['Sydney', 'Tokyo', 'Madrid']
cities1.append('Olso')
print(cities1) # prints ['Sydney', 'Tokyo', 'Madrid', 'Olso']
print(cities2) # prints ['Sydney', 'Tokyo', 'Madrid']

len() returns the length of an object. It is not a method of the list data type specifically, but it can be used to find the number of key-value pairs in a dictionary.

days=['Monday','Tuesday']
print(len(days)) # prints 2

4. LIST COMPREHENSIONS

List comprenhension allows for the creation of complex lists in a single line of code. It's an efficient way to create a new list

mylist=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

list2 = [ x**2 for x in mylist ]
print(list2) # prints [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    
list1 = [ x for x in mylist if x%3 == 0]
print(list1) # prints [3, 6, 9]

list3 = [x**2 for x in mylist if x < 5 ]
print(list3) # prints [1, 4, 9, 16]

list4 = [x for x in mylist if x not in [1,2,3] ]
print(list4) # prints [4, 5, 6, 7, 8, 9, 10]

mystring='hello world'

list5 = [x for x in mystring if x not in ['a','e','i','o','u']]
print(list5) # prints ['h', 'l', 'l', ' ', 'w', 'r', 'l', 'd']

list6 = [word[::-1] for word in mystring2.split()]
print(list6) # prints ['olleh', 'dlrow']

mylist = ['hello', '', 'world']
list7 = [word for word in mylist if word != '']
print(list7) # prints ['hello', 'world']

# filtering list for items with at least one alphanumeric character.
my_list = ['A1', 'bbb', '123', "''", '#']
new_list = [ item for item in my_list if any(caracter.isalnum() for caracter in item ) ]
print(new_list) # prints ['A1', 'bbb', '123']

# creating the coordinates of 8 equidistant points on the unit circle :
x = [np.cos(k * 2 * np.pi / 8) for k in range(8) ]
y = [np.sin(k * 2 * np.pi / 8) for k in range(8) ]

# combining strings using zip :
list7 = [letter + '....' + number for letter, number in zip('abcd','1234'[::-1])]
print(list7) # prints ['a....4', 'b....3', 'c....2', 'd....1']

# combining lists :
list8 = [(x, y) for x in [1, 2, 3] for y in ['a', 'b', 'c']]
print(list8) # prints [(1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'),
 (2, 'b'), (2, 'c'), (3, 'a'), (3, 'b'), (3, 'c')]

# creating a 2D array list object
list9 = [[1 for _ in range(1)] for _ in range(1)] 
print(list8) # prints [[1, 1, 1], [1, 1, 1], [1, 1, 1]]

# creating a list of .png files from a specific folder
import os
directory_path = '/path/folder'
png_files = [filename for filename in os.listdir(directory_path) if filename.endswith('.png')]

# listing files larger than 1 MB in a folder :
import os
dir_path = '/path/folder'
large_files = [file for file in os.listdir(dir_path) if os.path.getsize(os.path.join(dir_path, file)) > 1000000]

5. CODE SNIPPETS

code snippet for lists