Understanding Python Data Types: Sequences, Iterators, Conversions, and Comprehensions
This article provides a comprehensive overview of Python’s core data structures—including lists, dictionaries, tuples, sets, and strings—detailing their similarities, differences, conversion methods, and the use of comprehensions and concise conditional expressions to write more efficient and readable code.
In Python we frequently use containers such as lists and dictionaries to store data or reshape sequences, and these structures have various relationships. This article gives a systematic overview of the most common Python data types.
Similarities
All act as containers that can store data.
All can be iterated with for ... in loops.
Differences
Sequences store different types of data, while iterators store algorithms.
Sequences keep data in memory and are accessed via indexing or keys; iterators compute the next value on demand without storing data, making them more suitable for large‑scale processing.
Sequences allocate memory for each element; iterators allocate none, calculating each element when needed.
Sequences allow direct access via index or key; iterators only provide next() to retrieve the next value.
Trends
From left to right the diagrams illustrate ordering (unordered, ordered, rule‑based) and operation flexibility (full CRUD vs. read‑only only). Symbolic notation follows a size hierarchy: braces for dictionaries/sets, brackets for lists, parentheses for tuples, and quotes for strings.
Conversion Between Data Types
All types can be converted by calling the appropriate constructor, e.g., list(tuple) to turn a tuple into a list.
When converting to a dictionary, provide pairs of elements inside parentheses; a single element will raise an error.
Converting to a string with str(data) may not give the desired format; use join() to concatenate sequence elements into a string.
<code># Convert two lists into a dictionary using zip
lst1 = ['x','y','z'] # can be list, tuple, or set
lst2 = [123,234,345]
print(dict(zip(lst1,lst2)))
# Output: {'x': 345, 'y': 234, 'z': 123}</code>Concise Syntax – Comprehensions
Many data types support comprehensions, which build new iterables from existing ones in a compact expression.
Dictionary Comprehension
<code># Syntax
{operation_key: operation_value for key, value in dict if condition}
# Example
d = {'chinese': 88, 'math': 92, 'english': 93, 'history': 84}
print("Subjects with score >=90:", {k: 'Excellent' for k, v in d.items() if v >= 90})
# Output: {'math': 'Excellent', 'english': 'Excellent'}</code>Set Comprehension
<code># Syntax
{operation_key for x in set if condition}
# Example
s = {x**2 for x in [1, 2, 3]}
print("Set s:", s)
# Output: {1, 4, 9}</code>List Comprehension
<code># Syntax
[operation(x) for x in list if condition]
# Example
import random
print([random.randint(1,10)+x for x in range(0,10) if x % 2 == 0])
# Result (example): [3, 3, 14, 15, 12]
# Common forms:
# 1. [x for x in iterable]
# 2. [x for x in iterable if condition(x)]
# 3. [operation(x) for x in iterable if condition(x)]
# 4. [operation(x,y) for x in iterable for y in iterable1]</code>Generator Comprehension
<code># Syntax
(operation(x) for x in iterable if condition)
# Example
import random
print((random.randint(1,10)+x for x in range(0,10) if x % 2 == 0))
# Result: <generator object <genexpr> at 0x02FDC420>
# The generator can be iterated with a for‑loop or <code>next()</code>.</code>Combined Usage
These structures can be combined with conditional statements for compact logic.
<code># Simple if‑else
score = 92
if score >= 90:
print('Excellent')
else:
print('Good')
# Alternative conditional expressions
print(("Good", "Excellent")[score >= 90])
print({True: "Excellent", False: "Good"}[score >= 90])
print('Excellent' if eval("score >= 90") else 'Good')
# Output for all three: Excellent</code>- END -
Source: Internet, for learning purposes only. If any infringement occurs, please contact for removal.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.