VOOZH about

URL: https://dzone.com/articles/enumerate-and-zip-in-python

⇱ Enumerate and Zip in Python


Related

  1. DZone
  2. Coding
  3. JavaScript
  4. Enumerate and Zip in Python

Enumerate and Zip in Python

Want to learn about Python? Let's explore how `enumerate` and `zip` can simplify coding by helping you manipulate data in lists.

Likes
Comment
Save
3.9K Views

Join the DZone community and get the full member experience.

Join For Free

The built-in ‘enumerate’ function in Python allows us to iterate over a sequence such as a list, tuple, or string and it also keeps track of the current index of the current item.

Python
countries = ['USA', 'UK', 'Canada', 'Australia']

for index, country in enumerate(countries):
 print(f"Index: {index}, Country: {country}")

Index: 0, Country: USA
Index: 1, Country: UK
Index: 2, Country: Canada
Index: 3, Country: Australia


In the example, the ‘enumerate’ function is used in the ‘for’ loop to iterate over the ‘countries’ list. For each iteration, ‘enumerate’ returns the index and the corresponding element from the list.

Customizing Starting Index: We can also specify the starting index for the enumeration. 

Python
countries = ['USA', 'UK', 'Canada', 'Australia']

for index, country in enumerate(countries, start=2):
 print(f"Index: {index}, Country: {country}")

Index: 2, Country: USA
Index: 3, Country: UK
Index: 4, Country: Canada
Index: 5, Country: Australia


Key Reasons To Use ‘enumerate()’ in Python 

1. Accessing elements while Iterating: It simplifies accessing both the index and value of each item in a sequence simultaneously, and it eliminates the need for a separate counter variable, making code more concise and readable.

Python
countries = ['USA', 'UK', 'Canada', 'Australia']

for index, country in enumerate(countries):
 print(f"Index: {index}, Country: {country}")

Index: 0, Country: USA
Index: 1, Country: UK
Index: 2, Country: Canada
Index: 3, Country: Australia


2. Updating Elements in a List: Using ‘enumerate’ we can iterate over a list and also update elements. 

Python
numbers = [1, 2, 3, 4, 5]

for index, value in enumerate(numbers):
 numbers[index] = value * 2

print(numbers) # Output: [2, 4, 6, 8, 10]


3. Creating new sequences with Indices: We can use ‘enumerate()’ to construct new sequences that incorporate both the original values and their corresponding indices.

Python
countries = ['USA', 'UK', 'Canada', 'Australia']
list(enumerate(countries)) # [(0, 'USA'), (1, 'UK'), (2, 'Canada'), (3, 'Australia')]


4. Processing Files Line by Line: While reading a file and processing its contents line by line, we can use ‘enumerate’ to keep track of the line numbers. 

Python
with open('example.txt', 'r') as file:
 for line_number, line_content in enumerate(file, start=1):
 print(f"Line {line_number}: {line_content.strip()}")


enumerate() promotes clean, concise, and expressive code when working with sequences and indices in Python.

zip Function

The zip function is also a built-in Python function that processes elements simultaneously from multiple sequences, ensuring elements are accessed together. Using the zip function simplifies code and avoids nested loops or manual index-based tracking. 

Python
fruits = ["Apple", "Grape"]
prices = [25, 30]
for fruit, price in zip(fruits, prices):
 print(f"Fruit: {fruit}, Price: {price}")

#Fruit: Apple, Price: 25
#Fruit: Grape, Price: 30


Key Reasons To Use ‘zip()’ in Python

1. Creating Pairs or Tuples: zip is commonly used to pair elements from two or more lists, for ex:

Python
list1 = [1,2,3]
list2 = ['a', 'b', 'c']

pairs = list(zip(list1, list2))
print(pairs) # [(1, 'a'), (2, 'b'), (3, 'c')]


2. Creating Dictionaries: We can use 'zip' to create dictionaries by pairing keys and values from two separate lists.

Python
keys = ['name', 'age', 'city']
values = ['John', 25, 'New York']

user_info = dict(zip(keys, values))
print(user_info) # {'name': 'John', 'age': 25, 'city': 'New York'}


3. Iterating Over Multiple Lists Simultaneously: When you have two related lists (e.g., names and ages) and you want to process each pair of elements together.

Python
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]

for name, age in zip(names, ages):
 print(f"Name: {name}, Age: {age}")

Name: Alice, Age: 25
Name: Bob, Age: 30
Name: Charlie, Age: 35


4. Merging Data from Different Sources: Using 'zip' function, we can merge data from different sources and return a tuple. 

Python
list1 = [1,2,3]
list2 = ['a', 'b', 'c']
list(zip(list1, list2))
# [(1, 'a'), (2, 'b'), (3, 'c')]


5. Unzipping Lists: We can use 'zip' function to "unzip" a sequence of tuples into separate lists.

Python
tup = [(1, 'a'), (2, 'b'), (3, 'c')]
list1, list2 = zip(*tup)
print(list1) # (1, 2, 3)
print(list2) # ('a', 'b', 'c')


Handling Unequal Length IterablesWhen we use the zip function with iterables of different lengths, it stops creating tuples when the shortest input iterable is exhausted. The resulting iterator will have as many elements as the shortest input iterable. Any remaining elements from longer iterables are ignored.

Python
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c', 'd']
result = list(zip(list1, list2))
print(result) # [(1, 'a'), (2, 'b'), (3, 'c')]


zip() is a versatile function for working with multiple sequences in Python, promoting clean and efficient code. Its ability to combine, transpose, and unpack data makes it valuable in various programming tasks.

Element Enumerate (project) Processing Python (language) Strings Language code

Opinions expressed by DZone contributors are their own.

Related

  • Functional Programming Principles Powering Python’s itertools Module
  • Efficient String Formatting With Python f-Strings
  • How To Implement Cosine Similarity in Python
  • Difference Between High-Level and Low-Level Programming Languages

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

Let's be friends: