List Methods
Lists are a type of sequencing data that can contain other datatypes within.
List elements include:
1. indexed
2. mutable (changeable)
3. can contain duplicates
Return a list of numbers in sequence from a specified range:
In[]: nums = []
In[]: for i in range(0,10):
nums.append(i)
In[]: print(nums)
Out[]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Return the length of a list:
In[]: ex_lst = ['dog','fox','jumped'] ; ex_num_lst = [1,2,3]
In[]: print(len(ex_lst)) ; print(len(ex_str)); print(len(ex_num_lst))
Out[]:
3
3
Return the average length of a string in a list of strings:
In[]: s_2 = ['This', 'is', 'A','list','of', 'Strings', 'and', 'only', 'one','list','of', 'strings.']
In[]: avg_s_2 = sum(map(len, avg_s_2)) / len(avg_s_2)
In[]: avg_s_2
Out[]: 3.6666666666666665
Replace a range of items at a specified index with contents of an iterable:
In[]: ex_obj = ['dog','wing','foo','book','cat','bird']
In[]: ex_obj[1:4]='good'; print(ex_obj)
Out[]: ['dog', 'g', 'o', 'o', 'd', 'cat', 'bird']
Return a truth value for every item that starts with specific data:
In[]: ex_lst = ['dog', 'wing', 'foo', 'book', 'cat', 'bird', 'rhino']
In[]: for i in ex_lst:
print(i.startswith('b'), end=' ')
Out[]: False False False True False True False
Combine two lists of strings as a set (drops duplicates):
In[]: var1 = ['a' , 'b', 'c', 'd']
In[]: var2 = ['a' , 'b', 'e', 'f']
In[]: x = list(set(var1 + var2))
In[]: x
Out[]: ['f', 'd', 'c', 'a', 'e', 'b']
Return the index of duplicate items in a list:
In[]: var_str_lst = ['The', 'small', 'brown', 'fox', 'jumped',
'over','the','lazy','dog','and','the',
'dog','chased','the','fox']
In[]: [i for i,d in enumerate(var_str_lst) if d == 'the']
Out[]: [6, 10, 13]
Return all x items from a list of strings that exist at least once:
In[]: var_str_lst = ['The', 'small', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']
In[]: new_list = []
In[]: for i in var_str_lst:
new_list = [i for i in 'zaeiou']
In[]: print(new_list)
Out[]: ['z', 'a', 'e', 'i', 'o', 'u']
Merge two lists into a list of tuples:
In[]: keys_2 = ['year','name','subject','score'] ; values_2 = [1999,'Andrew','calculus',80]
In[]: lst_of_tup = list(zip(keys_2,values_2)) ; print(lst_of_tup)
Out[]: [('year', 1999), ('name', 'Andrew'), ('subject', 'calculus'), ('score', 80)]
Reverse the order of a list of strings:
In[]: lst_1 = ['a','b','c']
In[]: for i in reversed(lst_1):
print(i)
Out[]:
c
b
a
Iterate through a list and replace a specific value if found:
In[]: another_lst = ['dog','fox','jumped']
In[]: new_list = [i.replace('dog','lion') for i in another_lst]; print(new_list)
Out[]: ['lion', 'fox', 'jumped']
Convert a string item by index to a list of strings:
In[]: var_lst = ['The small brown fox jumped over the lazy dog','and then foobar', 'another string', 'last']
In[]: var_lst[0].split()
Out[]: ['The', 'small', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']
Append data to each string in a list of strings:
In[]: var_str_doo = [x + 'doo' for x in var_str] ; print(var_str_doo)
Out[]: ['Thedoo', 'smalldoo', 'browndoo', 'foxdoo', 'jumpeddoo', 'overdoo', 'thedoo', 'lazydoo', 'dogdoo']
Append a random list of int to an empty list:
In[]: import random
In[]: E = []
In[]: for i in random.sample(range(0,30),10): #a random number between 0 and 30 ten times.
E.append(i)
In[]: E
Out[]: [8, 5, 26, 23, 29, 6, 12, 2, 14, 22]
Return all items from a list that equal some data to a new list:
In[]: var_str_lst = ['The', 'small', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']
In[]: new_list = [i for i in var_str_lst if i == 'fox']; print(new_list)
Out[]: ['fox']
#Also works for list obj:
In[]: another_lst = ['dog','fox','jumped']
In[]: new_list_2 = [i for i in var_str_lst if i in another_lst]; print(new_list_2)
Out[]: ['fox', 'jumped', 'dog']
Remove unwanted data from a list of dirty strings:
In[]: dirty_lst_str = ['good $','#cats','&&bad','*** birds'] ; cleaned_lst_str = []
In[]: for i in dirty_lst_str:
cleaned_lst_str.append(i.strip(' $#&*'))
In[]: print(cleaned_lst_str)
Out[]: ['good', 'cats', 'bad', 'birds']
Nested list comprehension:
In[]: nested_lst = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
#Transpose rows and cols
In[]: [[row[i] for row in nested_lst] for i in range(4)]
Out[]: [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
#alt with built in functions
In[]: list(zip(*nested_lst))
Out[]: [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
Pass a list through a dictionary and return the values to a list:
In[]: alpha_dict = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j',
11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's',
20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z'}
In[]: ten_rand_nums = [5, 19, 20, 22, 13, 23, 4, 4, 10, 14, 9]
In[]: [alpha_dict[k] for k in ten_rand_nums]
Out[]: ['e', 's', 't', 'v', 'm', 'w', 'd', 'd', 'j', 'n', 'i']
Separate data into two plus lists from a mixed datatype list:
In[]: ex_1 = [1,2,3,'a','b','c',5,2,4,'x','5','z'] #mixed datatype list
In[]: def sep_funct_ex(mixed_data):
alpha = []
nums = []
for i in mixed_data:
try:
if float(i).is_integer() == True:
nums.append(i)
except ValueError:
alpha.append(i)
return [alpha, nums]
In[]:sep_data = sep_funct_ex(ex_1) #returns a nested list
In[]: sep_data
Out[]: [['a', 'b', 'c', 'x', 'z'], [1, 2, 3, 5, 2, 4, '5']]
Access data in nested list:
In[]: sep_data[0]
Out[]: ['a', 'b', 'c', 'x', 'z']
In[]: sep_data[0][0]
Out[]: 'a'
In[]: sep_data[1]
Out[]: [1, 2, 3, 5, 2, 4, '5']
In[]: sep_data[1][0]
Out[]: 1
In[]: alpha, nums = sep_funct_ex(ex_1) #returns alpha and nums in two separate list obj
In[]: alpha
Out[]: ['a', 'b', 'c', 'x', 'z']
In[]: nums
Out[]: [1, 2, 3, 5, 2, 4, '5']
Replace an item in a list at index x:
In[]: ex_obj = ['dog','wing','foo','book','cat','bird']
In[]: ex_obj[1] = 'good'; print(ex_obj)
Out[]: ['dog', 'good', 'foo', 'book', 'cat', 'bird']
Remove an item from a list at index x:
In[]: ex_obj = ['dog','wing','foo','book','cat','bird']
In[]: del ex_obj[4] ; print(ex_obj)
Out[]: ['dog', 'wing', 'foo', 'book', 'bird']
Remove all items in a list:
In[]: num_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In[]: num_list.clear() ; print(num_list)
Out[]: []
Convert list of strings to one string:
In[]: s_2 = ['This', 'is', 'A','list','of', 'Strings', 'and', 'only', 'one','list','of', 'strings.']
In[]: ListToStr = ' '.join(map(str,s_2))
In[]: ListToStr
Out[]: 'This is A list of Strings and only one list of strings.'
Access the first x items in a range:
In[]: for i in range(50,1000,50)[0:4]:
print(i)
Out[]:
50
100
150
200
Return every x item in a list of items:
In[]: var_str_lst = ['The', 'small', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']
In[]: print(var_str_lst[0::3])
Out[]: ['The', 'fox', 'the']
Sort a list alphabetically:
In[]: ex_lst = ['zed','poll','apple']
In[]: for i in sorted(ex_lst):
print(i, end=' ')
Out[]: apple poll zed
#ALT
In[]: ex_lst = [i for i in sorted(ex_lst)] ; print(ex_lst, end=' ')
Out[]: ['apple', 'poll', 'zed']
Some string formatting examples:
In[]: ex_var = 'dog' ; ex_var = ['dog','wing','foo','book','cat','bird']
In[]: '{0}'.format(ex_var) #returns the entire obj
Out[]: 'dog'
In[]: '{0}'.format(ex_var) #returns the entire obj
Out[]: "['dog', 'wing', 'foo']"
In[]: '{0[1]}'.format(ex_var_2) #returns an item in x position
Out[]: 'wing'
In[]: '{0[3]} , {0[0]} , {0[5]}'.format(ex_var) #returns multipul from dif positions
Out[]: 'book , dog , bird'
In[]: 'This is a string that inserts item {0[3]} from the object'.format(ex_var)
Out[]: 'This is a string that inserts item book from the object'
Add (append) an item to the end of a list:
In[]: ex_obj = ['dog','wing','foo','book','cat','bird']
In[]: ex_obj.append('rhino') ; print(ex_obj)
Out[]: ['dog', 'wing', 'foo', 'book', 'cat', 'bird', 'rhino']
Append items to a list from another list that start with specific data:
In[]: ex_lst = ['dog', 'wing', 'foo', 'book', 'cat', 'bird', 'rhino']
In[]: b_words = []
In[]: for i in ex_lst:
if i.startswith('b') == True:
b_words.append(i)
In[]: print(b_words)
Out[]: ['book', 'bird']
Count the number of a specific item in a list:
In[]: var_str_lst = ['The', 'small', 'brown', 'fox', 'jumped',
'over','the','lazy','dog','and','the',
'dog','chased','the','fox']
In[]: var_str_lst.count('fox')
Out[]: 2
Return all x items from a string to a list:
In[]: var_str = 'The small brown fox jumped over the lazy dog'
In[]: [i for i in var_str if i in 'aeiou']
Out[]: ['e', 'a', 'o', 'o', 'u', 'e', 'o', 'e', 'e', 'a', 'o']
Iterate through two or more list (or sequence data generally) with format():
In[]: lst_1 = ['a','b','c'] ;
In[]: lst_2 = ['first letter','second letter','third letter']
In[]: for i, p in zip(lst_1,lst_2):
print('{0} {1}'.format(i,p))
Out[]:
a first letter
b second letter
c third letter
Return the index postition of items in a list or series:
In[]: another_lst = ['dog','fox','jumped']
In[]: for i, v in enumerate(another_lst):
print(i,v)
Out[]:
0 dog
1 fox
2 jumped
Return conditioned integers from a list of integers:
In[]: num_lst = [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#Return all the even numbers from a list using list comp and modulo
In[]: evens = [i for i in num_lst if i%2 == 0] ; print(evens)
Out[]: [-10, -8, -6, -4, -2, 0, 2, 4, 6, 8] #modulo uses absolute values of int
#Return all the odd numbers from list using list comp and modulo
In[]: odds = [i for i in num_lst if i%2 != 0] ; print(odds)
Out[]: [-9, -7, -5, -3, -1, 1, 3, 5, 7, 9]
#Return all the nums divisible by x int:
In[]: by_3 = [i for i in num_lst if i%3 == 0]; print(by_3) #i%3 indicates the int that the must evenly div
Out[]: [-9, -6, -3, 0, 3, 6, 9]
#Return all nums with a comparison operator:
In[]: greater_than_5 = [i for i in num_lst if i > 5] ; print(greater_than_5)
Out[]: [6, 7, 8, 9]
#Return nums with a chained comparison operator:
In[]: more_than_2_less_than_7 = [i for i in num_lst if i > 2 and i < 7] ; print(more_than_2_less_than_7)
Out[]: [3, 4, 5, 6]
Convert a list to a set:
In[]: ListObj = ['The', 'small', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']
In[]: SetObj = set(ListObj)
In[]: SetObj
Out[]: {'The', 'brown', 'dog', 'fox', 'jumped', 'lazy', 'over', 'small', 'the'}
Generate a random list of integers:
In[]: import random
In[]: rand_int = []
In[]: for i in range(10):
rand_int_2.append(random.randrange(0,11))
In[]: print(rand_int)
Out[]: [6, 4, 10, 8, 3, 10, 4, 10, 2, 0]
List Comprehension syntax:
import random
[random.randint(1, 6) for _ in range(6)] #returns a list of 6 random numbers range(6); between 1 and 6 randint(1,6)
Convert two lists to a dictionary:
In[]: keys=[1,2,3] ; values=['a','b','c']
In[]: dictionary_ex = dict(zip(keys,values)) ; print(dictionary_ex)
Out[]: {1: 'a', 2: 'b', 3: 'c'}
Insert data to a given index into a list:
In[]: ex_lst_1 = [1,2,3,4,5,6]
In[]: ex_lst_1.insert(2,99) ; print(ex_lst_1)
Out[]: [1, 2, 99, 3, 4, 5, 6]
In[]: ex_lst_1.insert(2,'peeps') ; print(ex_lst_1)
Out[]: [1, 2, 'peeps', 99, 3, 4, 5, 6]
Pass each item in a list through a function using list comprehension:
In[]: var_int_lst = [1,2,3,4,5,6,7,8,9,10]
In[]: def ex_funct(some_int_val):
some_int_val = some_int_val + 5
return some_int_val
In[]: [ex_funct(i) for i in var_int_lst]
Out[]: [6, 7, 8, 9, 10, 11, 12, 13, 14, 15]