0% found this document useful (0 votes)
12 views3 pages

Python List Tuple Dictionary Code Examples

The document provides examples of basic operations on lists, tuples, and dictionaries in Python. It covers creating, modifying, and accessing elements in these data structures, as well as using list comprehension and dictionary comprehension. Each section includes code snippets demonstrating the respective operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views3 pages

Python List Tuple Dictionary Code Examples

The document provides examples of basic operations on lists, tuples, and dictionaries in Python. It covers creating, modifying, and accessing elements in these data structures, as well as using list comprehension and dictionary comprehension. Each section includes code snippets demonstrating the respective operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

List: Create and print a list

my_list = [1, 2, 3, 4, 5]

print(my_list)

List: Add element to a list

my_list = [1, 2, 3]

my_list.append(4)

print(my_list)

List: Remove element from a list

my_list = [1, 2, 3, 4]

my_list.remove(3)

print(my_list)

List: Sort a list

my_list = [3, 1, 4, 2]

my_list.sort()

print(my_list)

List: List comprehension

squares = [x**2 for x in range(5)]

print(squares)

List: Slicing a list

my_list = [0, 1, 2, 3, 4, 5]

print(my_list[1:4])

Tuple: Create and access a tuple

my_tuple = (1, 2, 3)

print(my_tuple[1])
Tuple: Tuple unpacking

a, b, c = (4, 5, 6)

print(a, b, c)

Tuple: Nested tuples

nested = ((1, 2), (3, 4))

print(nested[1][0])

Tuple: Iterate over tuple

my_tuple = (10, 20, 30)

for item in my_tuple:

print(item)

Dictionary: Create and access

my_dict = {'a': 1, 'b': 2}

print(my_dict['a'])

Dictionary: Add key-value pair

my_dict = {'x': 10}

my_dict['y'] = 20

print(my_dict)

Dictionary: Remove key

my_dict = {'k1': 1, 'k2': 2}

del my_dict['k1']

print(my_dict)

Dictionary: Iterate over keys and values

my_dict = {'a': 100, 'b': 200}

for k, v in my_dict.items():
print(k, v)

Dictionary: Dictionary comprehension

squares = {x: x**2 for x in range(5)}

print(squares)

You might also like