GreyMamba

Thinking Allowed … (under construction)

Thinking Allowed … (under construction)

Nothing is interesting if you're not interested
Helen Clark MacInnes
Python Stuff

I tend to spend too much time mucking around with Python code - as you can see from the bits of code scattered around this site. So, I've decided to add a page specifically for stuff related to just Python. It'll include snippets of code, interesting applications, algorithms or anything else Python related. Code that is purely there as a means to demonstrate or calculate something specific will remain as it is, in the most relevant post. Most of this stuff will be migrating to my sister pages -

- in the near future.

Sorry if you were hoping to see something on the Pythonidae family of snakes - interesting as they are.

Tips for Python lists

Just an HTML export from a Jupiter Notebook
Tips for Python lists

Lists - Tips and Tricks for Python

Here are some more advanced techniques you might find useful when manipulating lists. You don't need to know any of this in order to use lists productively, but they could come in useful.

The form of this notebook is by way of examples - with minimal explanation. Try the snippets out and experiment with the code to fully understand them.

Listing lists

In [11]:
# Unpacking a list of distances (ly)
distance = [37,522,313,1467,148,25]
print(distance)
print(distance[0], distance[3], distance[4])
Arcturus, Betelgeuse, Canopus, Deneb, Eltanin, Formalhaut = distance
print(Arcturus)
print(Deneb)
print(Eltanin)
[37, 522, 313, 1467, 148, 25]
37 1467 148
37
1467
148
In [12]:
# Add a names list
stars =['Arcturus', 'Betelgeuse', 'Canopus',
        'Deneb', 'Eltanin', 'Formalhaut']
# Separate the first 2 off from the rest
name1, name2, *therest = stars
print(name1)
print(name2)
print(therest)
Arcturus
Betelgeuse
['Canopus', 'Deneb', 'Eltanin', 'Formalhaut']

A neat way of printing out a list using a list comprehension

If you see '[None, None, None, None, None]' printed out at the end, this is a feature of Jupyter Notebooks. The statement above is returning a list of Nones (print() returns None).

In [13]:
[print(star) for star in stars]

print('\n***** a more complex example *****\n')

vel_m_per_sec = [169097.51972942502, 84524.93660185968, -0.0, -42244.6134347275, -126698.15570885541]
[print(f'Velocity: {v/1000:0.1f} km/s') for v in vel_m_per_sec]
Arcturus
Betelgeuse
Canopus
Deneb
Eltanin
Formalhaut

***** a more complex example *****

Velocity: 169.1 km/s
Velocity: 84.5 km/s
Velocity: -0.0 km/s
Velocity: -42.2 km/s
Velocity: -126.7 km/s
Out[13]:
[None, None, None, None, None]

Iterating through lists

In [14]:
for item in stars:
    print(item)

print('\n***** REVERSED *****\n')   
for item in stars[::-1]:
    print(item)
    
print('\n***** OR *****\n')
for item in reversed(stars):
    print(item)
Arcturus
Betelgeuse
Canopus
Deneb
Eltanin
Formalhaut

***** REVERSED *****

Formalhaut
Eltanin
Deneb
Canopus
Betelgeuse
Arcturus

***** OR *****

Formalhaut
Eltanin
Deneb
Canopus
Betelgeuse
Arcturus

With indices and/or multiple lists at once using 'zip()'

In [15]:
for i, item in enumerate(stars):
    print(i, item)

print("\n***** 2 lists *****\n")
for info in zip(stars, distance):
    print(info)
    
print("\n***** 2 lists together (using \'f\' strings *****\n")
for name, dist in zip(stars, distance):
    print(f'{name} is {dist} ly away')
0 Arcturus
1 Betelgeuse
2 Canopus
3 Deneb
4 Eltanin
5 Formalhaut

***** 2 lists *****

('Arcturus', 37)
('Betelgeuse', 522)
('Canopus', 313)
('Deneb', 1467)
('Eltanin', 148)
('Formalhaut', 25)

***** 2 lists together (using 'f' strings *****

Arcturus is 37 ly away
Betelgeuse is 522 ly away
Canopus is 313 ly away
Deneb is 1467 ly away
Eltanin is 148 ly away
Formalhaut is 25 ly away

Sorting multiple lists keeping their 'association' ... and, introducing 'map()'

In [16]:
print("\n***** Sort on first list (distance) zipped *****\n")
print(sorted(zip(distance,stars)))

print("\n***** or, using list comprehensions *****\n")
composorted = sorted(zip(stars,distance), key = lambda x:x[1])
print(composorted)

print("\n***** Split out again using list comprehensions *****\n")
newDistance = [i[1] for i in composorted]
newStars = [i[0] for i in composorted]
print('Sorted stars', newStars)
print('Sorted distances',newDistance)

print("\n***** Split out again using \'map\'' *****\n")
newStars, newDistance = map(list, zip(*composorted))
print('Sorted stars', newStars)
print('Sorted distances',newDistance)
***** Sort on first list (distance) zipped *****

[(25, 'Formalhaut'), (37, 'Arcturus'), (148, 'Eltanin'), (313, 'Canopus'), (522, 'Betelgeuse'), (1467, 'Deneb')]

***** or, using list comprehensions *****

[('Formalhaut', 25), ('Arcturus', 37), ('Eltanin', 148), ('Canopus', 313), ('Betelgeuse', 522), ('Deneb', 1467)]

***** Split out again using list comprehensions *****

Sorted stars ['Formalhaut', 'Arcturus', 'Eltanin', 'Canopus', 'Betelgeuse', 'Deneb']
Sorted distances [25, 37, 148, 313, 522, 1467]

***** Split out again using 'map'' *****

Sorted stars ['Formalhaut', 'Arcturus', 'Eltanin', 'Canopus', 'Betelgeuse', 'Deneb']
Sorted distances [25, 37, 148, 313, 522, 1467]

Sorting a list using a 'def' function or lambda function

You can pass a function/lambda to the sort/sorted functions to produce elaborate sorting algorithms. As an example, we could use this if we needed to sort a list of comma delimited lines stored in a list after reading a CSV file.

You could, of course, use this technique to sort using more complex functions.

NOTE: .sort() sorts in-situ, sorted() produces a new list

In [18]:
# Here's a toy example
# Let's say we want to sort on the numeric value taken from the 3rd 'field'
my_list = ['123,fred,678',
     '122,mary,-999',
     '713,joe,-567',
     '2,tiger,6']
print('Unsorted list',my_list)

# We can use a function
def third_field(line):
    return float(line.split(',')[2])

sorted_list_1 = sorted(my_list, key=third_field)
print('\nSorted list using a function', sorted_list_1)

# Or, using a lambda function
sorted_list_2 = sorted(my_list, key=lambda x: float(x.split(',')[2]))
print('\nSorted list using a lambda', sorted_list_2)

# Or, of course do it in-situ
print('\nOriginal list again', my_list)
my_list.sort(key=lambda x: float(x.split(',')[2]))
print('\nSorted in-situ becomes:', my_list)
Unsorted list ['123,fred,678', '122,mary,-999', '713,joe,-567', '2,tiger,6']

Sorted list using a function ['122,mary,-999', '713,joe,-567', '2,tiger,6', '123,fred,678']

Sorted list using a lambda ['122,mary,-999', '713,joe,-567', '2,tiger,6', '123,fred,678']

Original list again ['123,fred,678', '122,mary,-999', '713,joe,-567', '2,tiger,6']

Sorted in-situ becomes: ['122,mary,-999', '713,joe,-567', '2,tiger,6', '123,fred,678']
RapidWeaver Icon

Made in RapidWeaver

Back
 
RapidWeaver Icon

Made in RapidWeaver