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¶
# 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)
# 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)
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).
[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]
Iterating through lists¶
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)
With indices and/or multiple lists at once using 'zip()'¶
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')
Sorting multiple lists keeping their 'association' ... and, introducing 'map()'¶
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)
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
# 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)

Made in RapidWeaver