Range, Enumerate and Zip Functions

Range, Enumerate and Zip Functions

List function:

word = 'hello'
list(word) # Each character is added to a list

# To print each letter do:
for letter in list(word):
	print(letter) # This will print each letter as a stand alone item as it loops through

Range function:

for num in range(10): # Up to but not including the 10
	print(num) # Prints all the way up to 9

# Setting up a specific range:
for num in range(1,10): # Starts from 1 not from 0
	print(num)
	
# Setting up the step size (or increment):
for num in range(2, 10, 2): # Starts from 2 goes to 3 all the way up to 8
	print(num)
  • By default when using a number you can use just the range

  • The first position is reserved for the number from which you start from

  • The second position is the range up to BUT not included number that you want to go to

  • The third position is the increment by which the numbers should increase, by default this is 1

ZIP function:

  • Is used to zip two items together:

my_num = [1,2,3,4,5]
words = ['hello', 'my', 'name', 'is', 'tom']

combined_items = zip(mynum, words)
print(combined_items)

# What is this useful for?
for item in combined_items:
	print(item) # This generates a colection of tuples where all items are grouped
  • Combines each element in pairs of tuples like this:

my_num = [1,2,3,4,5]
words = ['hello', 'my', 'name', 'is', 'tom']

(1, 'hello')
(2, 'my')
(3, 'name')
(4, 'is')
(5, 'tom')
  • This is also known as enumeration

Enumerate function:

  • There is also a dedicated enumerate function in python:

words = ['hello', 'my', 'name', 'is', 'tom']

for item in enumerate(words):
	print(item) # This will print the below:
(0, 'hello')
(1, 'my')
(2, 'name')
(3, 'is')
(4, 'tom')
  • By default this starts with the Index position 0

  • If you want this to start with 1 do:

for item in enumerate(words, 1): # Starts with index pos 1
	print(item)

Last updated