Lists and Ranges (Cheat Sheet)

Examples

words = ["This", "is", "a", "list","of", "strings"]
print (words[0])
print (words[1])
print (words[2])
print (words[3])
print (words[4])
print (words[5])

print(words)

empty_list =[]
print(empty_list)

List with multiple types and dimensions

num = 3
my_list = ["a string", 2,[0, 1, 2, num], 3.14]
print(my_list[2][1])
print(my_list[3])

Indexing characters in strings like lists

str = "I am a string"
print(str[3])

Replicating lists like strings

li = [3, 2, 1, 0]
print (li * 3)

List operations

words = ["This", "is", "a", "list","of", "strings"]
print("is" in words)
print("is-not" in words)

numbers = [0, 1, 2, 3]
if 2 in numbers
   print("found it"
else:
   print(" did not find it")

for var in numbers:
   print(var)

List functions

numbers = [0, 1, 2]
numbers.append(4)
print(numbers)
print(len(numbers))
the_index = 3
numbers.insert(the_index, 3)
print(numbers)
numbers.append(55)
print(numbers.index(55))

List Slices

Create a sublist from index 0 to index 2. The second index is not included!

print(numbers[0:2])

Take a slice from the begin of a list

print(numbers[:2])

Take a slice from a start index to the end of a list

print(numbers[1:])

A step as a third parameter

a = [0, 1,2,3,4,5,6,7,8]
print(a[2:6:2])

The first and the second parameter can be empty. It execute things from the start or through the end of the list

List Comprehensions

squares = [i**2 for i in range(6)]
print(squares)

A comprehension with an if condition

squares = [i**2 for i in range(10) if i%2 == 0]
print(squares)

List Functions

>>> numbers = [99, 88, 77, 66 ]
>>> if all([i < 55 for i in numbers]):
...    print("All elements are smaller than 55")
...
>>> if any([i == 88 for i in numbers]):
...    print("Found 88!")
...
Found 88!
>>> for k in enumerate(numbers):
...    print(k)
...
(0, 99)
(1, 88)
(2, 77)
(3, 66)

Ranges

Important: ranges create objects. They do not create lists

n = list(range(3))
print(n)
n = list(range(3,8))
print(n)
n = list(range(4, 10, 2))
print(n)
  • 1 parameter: create an object which starts with 0 and ends one number below the argument
  • 2 parameter: create an object which starts with first argument and ends one number below the second argument
  • 3 parameter:create an object which starts with first argument and ends one number below the second argument. Third argument is step function which determines the intervall