Zum Hauptinhalt springen
Intelligence View
⚡ tsecurity.de Intelligence

Python for Beginners — Part 5: Collections

Part 5 of a beginner-friendly series on learning Python from scratch. In Part 4, we learned how to make decisions and repeat code with loops. Now we're going…

Beitrag
0
Seite
0
↗ Quelle (dev.to)
Quelle & Fakten · 7 Min. Lesezeit
Quelle: dev.to
Rubrik: Programmation sécurisée

Part 5 of a beginner-friendly series on learning Python from scratch.



In Part 4, we learned how to make decisions and repeat code with loops. Now we're going to upgrade that power dramatically: instead of working with single values, we'll work with entire collections of data.



This is where Python becomes truly versatile. Collections let you store multiple values in a single variable, organize data logically, and iterate over it with the loops you just learned. Most real programs spend their time managing collections.






Lists — Ordered, Changeable Collections



A list is a container that holds multiple values in a specific order. You can add, remove, or change items after creating the list.






Creating and accessing lists






fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]






Lists use square brackets and items are separated by commas. Items can be different types.



Access items by their index (position), just like strings:




fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[-1]) # cherry (last item)






Get the length with len():




print(len(fruits))  # 3









Slicing lists



Just like strings, lists can be sliced:




numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numbers[0:3]) # [1, 2, 3]
print(numbers[5:]) # [6, 7, 8, 9, 10]
print(numbers[::2]) # [1, 3, 5, 7, 9] (every 2nd item)









Essential list methods



Lists come with many built-in methods. Here are the most important:




fruits = ["apple", "banana"]

# Add items
fruits.append("cherry") # Add to the end
fruits.insert(1, "mango") # Insert at specific position
fruits.extend(["date", "elderberry"]) # Add multiple items

# Remove items
fruits.remove("banana") # Remove by value
fruits.pop() # Remove last item and return it
fruits.pop(0) # Remove item at index 0
fruits.clear() # Remove all items

# Find and sort
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(numbers.count(1)) # 2 (how many 1's)
print(numbers.index(4)) # 2 (position of 4)
numbers.sort() # Sort in place: [1, 1, 2, 3, 4, 5, 6, 9]
numbers.reverse() # Reverse in place

# Create a copy
numbers_copy = numbers.copy() # Independent copy






Important: sort() and reverse() change the list itself, not creating a new list. If you want to keep the original:




sorted_numbers = sorted(numbers)     # Returns a new sorted list









Modifying list items



Lists are mutable (changeable):




fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry" # Change the second item
print(fruits) # ["apple", "blueberry", "cherry"]









Iterating over lists



Combine lists with the for loops from Part 4:




fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
print(fruit)






Output:




apple
banana
cherry









List comprehension — concise list creation



List comprehension is a compact way to create a new list by transforming or filtering an existing one:




# Create a list of squares
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares) # [1, 4, 9, 16, 25]

# Filter: only even numbers
evens = [x for x in numbers if x % 2 == 0]
print(evens) # [2, 4]

# Transform and filter
result = [x * 2 for x in numbers if x > 2]
print(result) # [6, 8, 10]






Read it as: "Create a list of [transformation] for [each item] in [source list] if [condition]"



List comprehensions are faster and more Pythonic than building lists with loops. They're common in real code.






Tuples — Ordered, Unchangeable Collections



A tuple is like a list, but immutable (unchangeable). Once created, you can't add, remove, or modify items.






Creating tuples






colors = ("red", "green", "blue")
single_item = ("hello",) # Note the comma — without it, it's just a string
empty = ()






Use parentheses (round brackets). The comma is crucial for single-item tuples.






Accessing and iterating






colors = ("red", "green", "blue")
print(colors[0]) # red
print(colors[-1]) # blue
print(len(colors)) # 3

for color in colors:
print(color)









Unpacking tuples



Tuples shine when you want to assign multiple values at once:




x, y = (1, 2)
print(x) # 1
print(y) # 2

# The parentheses are optional
name, age, city = "Ramesh", 25, "Chennai"
print(name, age, city) # Ramesh 25 Chennai

# Swap variables easily
a, b = 1, 2
a, b = b, a # Now a=2, b=1









Why use tuples?





  • Speed: Slightly faster than lists (minor difference)


  • Safety: Immutable, can't accidentally modify


  • Keys in dictionaries: Tuples can be dict keys; lists can't


  • Function returns: Functions often return tuples of multiple values




def get_user():
return ("Ramesh", 25, "Chennai")

name, age, city = get_user()









Sets — Unique, Unordered Collections



A set is a collection of unique values with no specific order. Duplicates are automatically removed.






Creating sets






numbers = {1, 2, 3, 4, 5}
unique_letters = {"a", "b", "c", "a"} # 'a' appears once
print(unique_letters) # {'a', 'b', 'c'} (order may vary)

empty_set = set() # Note: {} creates an empty dict, not a set






Use curly braces. Sets have no indexing — you can't access the first item like you can with lists.






Common set operations






a = {1, 2, 3}
b = {3, 4, 5}

# Union — all items from both sets
print(a | b) # {1, 2, 3, 4, 5}
print(a.union(b)) # {1, 2, 3, 4, 5}

# Intersection — items in both sets
print(a & b) # {3}
print(a.intersection(b)) # {3}

# Difference — items in a but not b
print(a - b) # {1, 2}
print(a.difference(b)) # {1, 2}

# Check membership
print(3 in a) # True
print(4 in a) # False









Set methods






numbers = {1, 2, 3}
numbers.add(4) # Add one item
numbers.update([5, 6]) # Add multiple items
numbers.remove(2) # Remove item (error if not found)
numbers.discard(10) # Remove item (no error if not found)
numbers.clear() # Remove all items









Use cases for sets





  • Remove duplicates: unique = set([1, 2, 2, 3, 3, 3]) → {1, 2, 3}


  • Check membership: Sets are faster than lists for in checks


  • Mathematical operations: Union, intersection, difference






Dictionaries — Key-Value Pairs



A dictionary stores pairs of keys and values. You access values using their keys, not positions.






Creating dictionaries






person = {
"name": "Ramesh",
"age": 25,
"city": "Chennai"
}

scores = {"math": 95, "science": 87, "history": 92}
empty = {}






Use curly braces with key: value pairs. Keys are usually strings; values can be any type.






Accessing and modifying






person = {"name": "Ramesh", "age": 25}

print(person["name"]) # Ramesh
print(person["age"]) # 25

# Modify existing key
person["age"] = 26

# Add new key
person["city"] = "Chennai"

# Try to access non-existent key (safer way)
person.get("phone") # None (no error)
person.get("phone", "N/A") # N/A (default value)









Dictionary methods






person = {"name": "Ramesh", "age": 25, "city": "Chennai"}

# Get all keys, values, or pairs
print(person.keys()) # dict_keys(['name', 'age', 'city'])
print(person.values()) # dict_values(['Ramesh', 25, 'Chennai'])
print(person.items()) # dict_items([('name', 'Ramesh'), ('age', 25), ...])

# Iterate
for key in person:
print(f"{key}: {person[key]}")

# Iterate over pairs
for key, value in person.items():
print(f"{key}: {value}")

# Remove items
person.pop("age") # Remove and return value
person.popitem() # Remove last pair
person.clear() # Remove all

# Update from another dict
person.update({"phone": "555-1234", "age": 26})









Nested dictionaries



Dictionaries can contain other dictionaries (or lists, or tuples):




team = {
"player1": {"name": "Ramesh", "score": 95},
"player2": {"name": "Priya", "score": 87},
"player3": {"name": "Arun", "score": 92}
}

print(team["player1"]["name"]) # Ramesh
print(team["player2"]["score"]) # 87









Choosing the Right Collection











































Collection Ordered Changeable Duplicates Use Case
List ✓ ✓ ✓ Store sequence of items
Tuple ✓ ✗ ✓ Immutable sequences, dict keys
Set ✗ ✓ ✗ Unique values, membership checks
Dict ✓ (Python 3.7+) ✓ ✓ (values) Store labeled data, key-value lookup





Practical Examples






Example 1: Managing a to-do list






todos = []

# Add tasks
todos.append("Buy groceries")
todos.append("Finish project")
todos.append("Call mom")

# Mark as done (remove)
todos.remove("Buy groceries")

# Show remaining
for i, task in enumerate(todos):
print(f"{i+1}. {task}")






Output:




1. Finish project
2. Call mom









Example 2: Count word frequency






text = "the quick brown fox jumps over the lazy dog the fox"
words = text.split()
word_count = {}

for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1

print(word_count)
# {'the': 3, 'quick': 1, 'brown': 1, 'fox': 2, ...}






Or more concisely:




from collections import Counter
word_count = Counter(words)
print(word_count)









Example 3: Find common interests






alice_interests = {"python", "music", "hiking", "gaming"}
bob_interests = {"python", "gaming", "cooking", "music"}

# What do they both enjoy?
common = alice_interests & bob_interests
print(common) # {'python', 'gaming', 'music'}

# What does Alice enjoy that Bob doesn't?
alice_unique = alice_interests - bob_interests
print(alice_unique) # {'hiking'}









Why This Matters



Collections are fundamental to every real program. You'll spend most of your programming time manipulating lists, dictionaries, and sets. Once you internalize which tool is right for each job, you'll write cleaner, faster code.



The most common beginner mistakes:




  • Confusing list and tuple syntax ([] vs ())

  • Trying to add items to a tuple (they're immutable!)

  • Using {} for an empty set and getting a dict instead

  • Trying to use lists as dictionary keys (they're unhashable)

  • Forgetting that dictionaries store by key, not position






This is Part 5 of an 8-part beginner Python series. Catch up on Part 1: Getting Started & Syntax, Part 2: Variables, Data Types & Numbers, Part 3: Strings & Booleans, and Part 4: Operators & Control Flow.

Social ReaktionenReagiere als Erste:r — dein Feedback zählt!
Informations-Bewertung:
✏️ Information ergänzen
🛡️ Versioniert via CMS-Revisions-Engine (Freigabe-Queue für Gäste)

💬 Discussion communautaire et commentaires

🌐 Rejoindre le chat principal

Lancez la discussion dans le flux diffusé du Social Chat ou proposez ci-dessus une contribution experte via le formulaire de complément.

Briefing sécurité Gratuit · désabonnement en 1 clic

Intelligence Digest — gratuit

Chaque jour, les principales actualités sécurité · résiliable à tout moment

Évaluation communautaire & preuve sociale
⭐ Avis des lecteurs
–
Ø / 5.0
Pas encore d'évaluation des lecteurs
Cet article vous a-t-il été utile ?
0
Donner votre évaluation
Évaluation détaillée (facultatif)
Contenu & qualité
Source & fiabilité
Actualité

Groupes d’histoires apparentées & sources (IA vectorielle)

6 Cluster
19 sources
Bluetti Black Friday: Drei empfehlenswerte Powerstations günstiger
ifun.de il y a 21 min.
18 autres sources
CNETil y a 21 hI Test Air Fryers. Cuisinart’s Glass Model Is a Steal at $84 for Black Friday t3n.deil y a 1 hBlack Friday: Diese 9 Fritzboxen, Repeater und Co. sind wirklich günstig Golem.deil y a 52 min.Anzeige: Leises Rudergerät zum Black Friday günstig wie nie bei Amazon heise online Newsil y a 41 min.Black Friday: Bei Saugrobotern kräftig sparen – Topmodelle zum Tiefstpreis AppleInsider Newsil y a 40 min.Black Friday price war drops Apple's M6 MacBook Pro to $1,779 WinFuture Newsil y a 1 hBlack-Friday-Deal: Lymow One Plus, der Panzer unter den Mährobotern netzwelt.deil y a 2 hXiaomi TV F Pro im Black-Friday-Check: Wie gut ist der Fernseher-Hit wirklich? netzwelt.deil y a 1 hWer eine Nintendo Switch 2 sucht, sollte sich diese Black-Friday-Aktion bei congstar anschauen Computer Bildil y a 1 hBlack Friday: Die besten Girokonto-Deals PC-WELTil y a 1 hAmazon Black Friday Woche am Dienstag: Die besten Technik-Deals im Überblick PC-WELTil y a 1 hFritzbox 7690 mit Wi-Fi 7 bei Amazon im Black-Friday-Angebot: Jetzt deutlich günstiger Latest from TechRadaril y a 1 hProton VPN Plus vs Surfshark One: which plan is the better Black Friday deal right now? Latest from TechRadaril y a 1 hBlack Friday Oura Ring deals: The best of the deals so far, picked by a wearable-tech expert CNETil y a 6 ansOur Favorite Blenders of 2026 Are on Sale Ahead of Black Friday CNETil y a 1 hBrighten Up Your Day by Saving 20% Off Flashlights With Olight’s Black Friday Sale CNETil y a 1 hLive: Black Friday Deals Are Here. Shop Expert Picks Across Tech, Everyday Essentials and More at Up to 60% Off Golem.deil y a 1 hAnzeige: Logitech-Tastatur MX Keys S am Black Friday zum Sensationspreis auf Amazon PC-WELTil y a 2 hLuminar zum Black Friday: KI-Bildbearbeitung für nur 79,20 Euro
17 sources
CVE-2026-133764 | Twig up to 3.31.0 Sandbox toString sandbox (EUVD-2026-133913)
VulDB Updates il y a 51 min.
16 autres sources
VulDB Updatesil y a 51 min.CVE-2026-133763 | Symfony Twig up to 3.31.0 Sandbox toString sandbox (EUVD-2026-133912) VulDB Updatesil y a 51 min.CVE-2026-132270 | Significant-Gravitas AutoGPT up to 0.8.4 Autopilot authorization (EUVD-2026-133583) VulDB Updatesil y a 51 min.CVE-2026-136123 | Friendica up to 2026.05-1 ActivityPub compactProfile input validation (EUVD-2026-133909) VulDB Updatesil y a 51 min.CVE-2026-136124 | welovemedia ffmate up to 2.0.x wildcardReplacer argument injection (EUVD-2026-133908) VulDB Updatesil y a 1 hCVE-2026-72522 | Libexpat up to 2.8.2 Unicode *_toUtf16 out-of-bounds (EUVD-2026-54990 / Nessus ID 385514) VulDB Updatesil y a 1 hCVE-2026-133773 | Twig markdown-extra up to 3.31.0 HtmlConverter html_to_markdown options resource consumption (EUVD-2026-133922) VulDB Updatesil y a 1 hCVE-2026-133772 | Twig up to 3.30.x Sandbox sandbox (EUVD-2026-133921) VulDB Updatesil y a 1 hCVE-2026-133770 | Twig up to 3.31.0 Sandbox __construct sandbox (EUVD-2026-133919) VulDB Updatesil y a 1 hCVE-2026-133769 | Symfony html-extra up to 3.31.0 Cva Cva::apply sandbox (EUVD-2026-133918) VulDB Updatesil y a 1 hCVE-2026-133767 | Twig up to 3.31.0 Sandbox __toString sandbox (EUVD-2026-133916) VulDB Updatesil y a 1 hCVE-2026-133766 | Twig up to 3.31.0 Sandbox toString sandbox (EUVD-2026-133915) VulDB Updatesil y a 1 hCVE-2026-133765 | Symfony Twig up to 3.31.0 Sandbox sandbox (EUVD-2026-133914) VulDB Updatesil y a 2 hCVE-2026-13137 | Hitachi Energy RTU500 CMU up to 13.9.1 User management/REST resolver/SPA-Bus buffer overflow (EUVD-2026-133827) VulDB Updatesil y a 2 hCVE-2026-131717 | Liquid Web, StellarWP Event Tickets Plugin up to 5.31.1 on WordPress authorization (EUVD-2026-131354) VulDB Updatesil y a 2 hCVE-2026-126605 | Proton Pass up to 1.21.0 Face ID App Lock improper authentication (EUVD-2026-133826) VulDB Updatesil y a 2 hCVE-2026-103406 | Juniper Session Smart Conductor up to 7.0.4/7.1.6/7.2.2 AutomatedProvisioner os command injection (EUVD-2026-112215)
Articles similaires
🔍 Verwandte News

Auch interessante Nachrichten Python for Beginners — Part 5: Collections

Thematisch verwandte Begriffe: Python, Beginners, Part, Collections · 6 Treffer

Laden...

Chargement des vidéos ...

Laden...

Chargement des articles ...

Laden...

Chargement des vidéos ...

Laden...

Chargement des articles ...

Laden...

Chargement des vidéos ...

Laden...

Chargement des articles ...

Laden...

Chargement des vidéos ...

Laden...

Chargement des articles ...

Laden...

Chargement des vidéos ...

💬 Chargement des commentaires…
Sentinel CTI: ONLINE
Tirer pour actualiser
Widgets & Topics
Loading widgets…
Nächster Beitrag