Python More About Lists

List Comprehensions

One way to create a list with for loop:

>>> new_list = []
>>> old_list = [1, 2, 3, 4]
>>> for each in old_list:
...     new_list.append(each**2)
...
>>> new_list
[1, 4, 9, 16]

List comprehensions are an elegant way to build a list without having to use another list for loops to append values one by one.

>>> old_list = [1, 2, 3, 4]
>>> new_list = [each**2 for each in old_list]
>>> new_list
[1, 4, 9, 16]

Multiple Assignment

>>> list = ['one', 'two', 'three']
>>> one, two, three = list
>>> one
'one'
>>> two
'two'
>>> three
'three'

For loops

For loop over the list:

>>> list = [1,2,3,4,5]
>>> for each in list:
...     print(each)
...
1
2
3
4
5
>>>

I never liked i=0, i+=1 structure, but if you still need to track the index:

>>> list = [1,2,3,4,5]
>>> for i, item in enumerate(list):
...     print(f'{i} - {item}')
...
0 - 1
1 - 2
2 - 3
3 - 4
4 - 5

Nested lists

>>> list = [ 1, 2, 3, [11, 22, 33, [111, 222, 333, 444]]]
>>> list[3]
[11, 22, 33, [111, 222, 333, 444]]
>>> list[3][0]
11
>>> list[3][3]
[111, 222, 333, 444]
>>> list[3][3][3]
444

Sets

set – unique collection of elements – an unordered collection type. Sets are used for membership testing and eliminating duplicate entries.

my_set = {"one", "two", "three"}
  • no access using an index, use for loop
  • once created – cannot change items, but can add new items my_set.add(‘new item’). or .update() for multiple items
>>> list = [1,2,3,1,2,3,1,2,3,1,2,3,1,2,3]
>>> set(list)
{1, 2, 3}
>>> str = '123123123'
>>> set(str)
{'2', '1', '3'}

The membership test is faster for sets because has is implemented using a hash table.

timeit module allows measuring the execution time of small code snippets

import timeit
def my_function():
  pass
print(timeit.timeit(my_function, number=100000))
# will run the code a set number of times
>>> import timeit
>>> timeit.timeit('3 in list', setup='list = [1, 2, 3, 4, 5, 6, 7, 8, 9];my_set=set(list)')
0.13245909999977812
>>> timeit.timeit('3 in my_set', setup='list = [1, 2, 3, 4, 5, 6, 7, 8, 9];my_set=set(list)')
0.07676899999978559

From the post about basic python terms:

# Last element
>>> l = ['aaa', 'bbb', 'ccc']
>>> l[-1]
'ccc'

# Change element with index
>>> l[0] = 'ddd'
>>> l
['ddd', 'bbb', 'ccc']

# Inserting Elements into a List
>>> l.insert(0, 'aaa')
>>> l
['aaa', 'ddd', 'bbb', 'ccc']

# Remove element by index
>>> del l[1]
>>> l
['aaa', 'bbb', 'ccc']

# Remove element with pop if need to use removed element after pop
# pop() - last element
# pop(index)
>>> popped_l=l.pop(2)
>>> l
['aaa', 'bbb']
>>> popped_l
'ccc'

# Remove element by name -> remove (only the first occurrence of the value you specify)
>>> removed_l = l.remove('aaa')
>>> l
['bbb']

# To remove all 2 from the list - while loop with remove in it:
>>> l = [1, 2, 3, 1, 2, 2, 3, 4, 5]
>>> l
[1, 2, 3, 1, 2, 2, 3, 4, 5]
>>> while 2 in l:
...     l.remove(2)
...
>>> l
[1, 3, 1, 3, 4, 5]

# Sort() - sort and permanently change the list, no way to revert
# l.sort(reverse=True) - reverse alphabetical order
>>> l = ['bbb', 'aaa', 'ccc', 'ddd']
>>> l.sort()
>>> l
['aaa', 'bbb', 'ccc', 'ddd']

# Need Temporarily - sorted()
>>> l
['bbb', 'aaa', 'ccc', 'ddd']
>>> print(sorted(l))
['aaa', 'bbb', 'ccc', 'ddd']
>>> l
['bbb', 'aaa', 'ccc', 'ddd']

# Reverse Order
>>> l
['ddd', 'ccc', 'aaa', 'bbb']
>>> l.reverse()
>>> l
['bbb', 'aaa', 'ccc', 'ddd']
>>> l.reverse()
>>> l
['ddd', 'ccc', 'aaa', 'bbb']

# Range, step and even numbers
>>> even_numbers = list(range(2,11,2))
>>> print(even_numbers)
[2, 4, 6, 8, 10]
>>> min(even_numbers)
2
>>> max(even_numbers)
10
>>> sum(even_numbers)
30


#List Comprehensions
>>> squares = [value**2 for value in range(1,11)]
>>> print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

or

>>> squares = []
>>> for value in range(1,11):
...     squares.append(value**2)
...
>>> print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# Copy list, l = l_copy will create just var to the same list
>>> l
['ddd', 'ccc', 'aaa', 'bbb']
>>> l_copy = l[:]
>>> l
['ddd', 'ccc', 'aaa', 'bbb']
>>> l_copy
['ddd', 'ccc', 'aaa', 'bbb']
>>> l_copy.append('eee')
>>> l
['ddd', 'ccc', 'aaa', 'bbb']
>>> l_copy
['ddd', 'ccc', 'aaa', 'bbb', 'eee']
Share

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *