Fundamentals 13 min read

Master Python Lists, Tuples, and Dictionaries: Essential Guide with Code Examples

This article introduces Python’s core data structures—lists, tuples, and dictionaries—explaining their definitions, indexing, slicing, iteration, modification, and common operations, and provides clear code examples for creating, accessing, updating, and deleting elements, helping beginners deepen their programming fundamentals.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Python Lists, Tuples, and Dictionaries: Essential Guide with Code Examples

Preface

Previously we briefly covered strings and numbers; this article discusses the remaining basic data types in Python: lists, tuples, and dictionaries.

List

Lists are defined with square brackets [], elements are separated by commas, and any data type (except sets) can be nested.

# Define a list
li = ['a', 1, True, ('b', 'c'), [1, 2, 3], {'name': '咸鱼'}, {1, 2}]
# Iterate
for i in li:
    # Print type and value
    print(type(i), i)

List indexing

# Define a list
li = ['a', 1, True, ('b', 'c'), [1, 2, 3], {'name': '咸鱼'}, {1, 2}]
# Access by index (0‑based)
temp1 = li[0]
print(temp1)  # a
# Access nested list element
temp2 = li[4][0]
print(temp2)  # 1
# Slice (returns a list)
temp3 = li[1:5]
print(temp3)  # [1, True, ('b', 'c'), [1, 2, 3]]

List traversal

# Recommended way
for i in li:
    print(i)
# Using while and index
j = 0
while j < len(li):
    print(li[j])
    j += 1

List modification

# Mutable list example
li = ['a', 'b', 'c']
li[0] = 'b'
print(li)
# Slice assignment
li[0:2] = ['c', 'c']
print(li)
# Immutable example (will raise TypeError)
str1 = 'abc'
print(str1[0])
# str1[0] = '1'  # TypeError

List deletion

# Delete by index
li = ['a', 'b', 'c']
 del li[0]
print(li)
# pop() returns removed value
li = ['a', 'b', 'c']
temp1 = li.pop()
print(li, temp1)
temp2 = li.pop(0)
print(li, temp2)
# remove() deletes first matching value
li = [11, '22', 22, 33, 44, 22]
li.remove(22)
print(li)
# clear entire list
li = ['a', 'b', 'c']
li.clear()
print(li)

List insertion

# Insert at specific index
li = [1, 2, 3, 4, 5, 6]
li.insert(2, 'lll')
print(li)
# Append single element
li.append('aaa')
li.append([11, 22, 33])
print(li)
# Extend with iterable
li.extend('aaa')
li.extend([11, 22, 33])
print(li)
# Concatenate two lists
li1 = [1, 2, 3, 4]
li2 = ['a', 'b', 'c', 'd']
li3 = li1 + li2
print(li3)

List query

# Membership test
li = [1, 2, 3, 4]
res = 2 in li
print(res)
# Count occurrences
li = [1, 2, 2, 3, 2, 2, 3, 4]
res = li.count(2)
print(res)
# Index of first occurrence
li = [1, 2, 3, 4]
res = li.index(2)
print(res)

List reversal

li = [1, 'a', 2, 'b']
li.reverse()
print(li)

List sorting and min/max

# Sorting numeric list
li = [8, 2, 6, 8, 5]
li.sort()
print(li)
# Sorting string list
li = ['b', '5', 'z', 'y', 'r', 'l']
li.sort()
print(li)
print(max(li))
print(min(li))

List ↔ string conversion

# List from string
str1 = 'abcdefg'
li = list(str1)
print(li)
# String from list of strings
li = ['1', 'a', 'c']
s1 = ''.join(li)
print(s1)
# Concatenate mixed types
li = [1, 2, 'a', 'b']
s1 = ''
for i in li:
    s1 += str(i)
print(s1)

Tuple

Tuples are immutable sequences defined with parentheses (). They can contain any data type, be indexed, sliced, and iterated, but cannot be modified.

tu = (111, "aaa", (11, 22, 33), [(1, 2, 3)], 222, True, 333)

Common tuple methods:

count(a)   # Number of occurrences of a
index(a, start, end)   # Index of a within optional slice

Good practice: add a trailing comma for single‑element tuples, e.g., tu = (1, 2, 3,).

Dictionary

Dictionaries use curly braces {} and consist of key‑value pairs. Keys must be unique and immutable; values can be any type, and dictionaries can be nested.

dic = {
  'k1': 'v1',
  'k2': 'v2',
  'k3': 'v3',
  'k2': 'v4',   # later key overwrites earlier
  False: 'aa',
  0: 'bb',
  'k4': [1, 2, 3, 4],
  'k5': {'k1': 'v1'}
}
print(dic)

Access

# Access nested values
print(dic['k5']['k1'])   # v1
print(dic['k4'][0])      # 1
# Missing key raises KeyError
# Use get() to avoid exception
print(dic.get('kkkk'))          # None
print(dic.get('kkkk', '不存在')) # '不存在'

Iteration

# Iterate over keys (default)
for i in dic:
    print(i)
# Iterate over values
for v in dic.values():
    print(v)
# Iterate over items
for k, v in dic.items():
    print(k, v)

fromkeys

# Create dict from keys
dic0 = dict.fromkeys('a')               # values default to None
dic1 = dict.fromkeys('a', 'b')
print(dic0, dic1)
# Using iterable of keys
dic3 = dict.fromkeys(['a','b','c'], [1,2,3])
print(dic3)

Add

# Add or update key
dic['k4'] = 'v4'
print(dic)
# setdefault returns existing value or adds new one
v1 = dic.setdefault('k1', 'v111')
print(dic, v1)
v2 = dic.setdefault('k123', 'v123')
print(dic, v2)

Modify

# Overwrite existing key
dic['k1'] = 'v111'
print(dic)
# update with another dict
dic.update({'k2': 'v222'})
print(dic)
# update multiple keys
dic.update({'k3': 'v333', 'k4': 'k4444'})
print(dic)
# keyword arguments
dic.update(k5='k555')
print(dic)
# Adding new key via update
dic.update(k6='k666')
print(dic)

Delete

# pop returns removed value
res = dic.pop('k1')
print(dic, res)
# pop with default to avoid exception
res = dic.pop('k111', 'key不存在')
print(dic, res)
# popitem removes last inserted pair
k, v = dic.popitem()
print(dic, k, v)
# clear all entries
dic.clear()
print(dic)

Summary

The article covered Python’s fundamental mutable and immutable containers—lists, tuples, and dictionaries—demonstrating creation, indexing, slicing, iteration, modification, and common operations with practical code snippets.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonData Structuresprogramming fundamentalsListdictionarytuple
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.