3 1-Lists
3 1-Lists
ipynb - Colab
1. Introduction to Lists
2. Creating Lists
3. Accessing List Elements
4. Modifying List Elements
5. List Methods
6. Slicing Lists
7. Iterating Over Lists
8. List Comprehensions
9. Nested Lists
10. Practical Examples and Common Errors
lst=[]
print(type(lst))
<class 'list'>
names=["Krish","Jack","Jacob",1,2,3,4,5]
print(names)
mixed_list=[1,"Hello",3.14,True]
print(mixed_list)
fruits=["apple","banana","cherry","kiwi","gauva"]
print(fruits[0])
print(fruits[2])
print(fruits[4])
print(fruits[-1])
apple
cherry
gauva
gauva
print(fruits[1:])
print(fruits[1:3])
fruits[1]="watermelon"
print(fruits)
fruits[1:]="watermelon"
https://colab.research.google.com/drive/11Faup-xQ_1t0LtzlCQBbYyWPZnOWzUKW#printMode=true 1/4
7/18/24, 9:34 AM 3.1-Lists.ipynb - Colab
fruits
['apple', 'w', 'a', 't', 'e', 'r', 'm', 'e', 'l', 'o', 'n']
fruits=["apple","banana","cherry","kiwi","gauva"]
## List Methods
fruits.insert(1,"watermelon")
print(fruits)
orange
['apple', 'watermelon', 'banana', 'cherry', 'kiwi', 'gauva']
index=fruits.index("cherry")
print(index)
fruits.insert(2,"banana")
print(fruits.count("banana"))
fruits
fruits
fruits
print(fruits)
[]
## Slicing List
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numbers[2:5])
print(numbers[:5])
print(numbers[5:])
i t( b [ 2])
https://colab.research.google.com/drive/11Faup-xQ_1t0LtzlCQBbYyWPZnOWzUKW#printMode=true 2/4
7/18/24, 9:34 AM 3.1-Lists.ipynb - Colab
print(numbers[::2])
print(numbers[::-1])
[3, 4, 5]
[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
[1, 3, 5, 7, 9]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
numbers[::3]
[1, 4, 7, 10]
numbers[::-2]
[10, 8, 6, 4, 2]
1
2
3
4
5
6
7
8
9
10
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
## List comprehension
lst=[]
for x in range(10):
lst.append(x**2)
print(lst)
Nested List Comprehension [expression for item1 in iterable1 for item2 in iterable2]
https://colab.research.google.com/drive/11Faup-xQ_1t0LtzlCQBbYyWPZnOWzUKW#printMode=true 3/4
7/18/24, 9:34 AM 3.1-Lists.ipynb - Colab
print(lst)
[0, 2, 4, 6, 8]
[0, 2, 4, 6, 8]
lst1=[1,2,3,4]
lst2=['a','b','c','d']
print(pair)
[[1, 'a'], [1, 'b'], [1, 'c'], [1, 'd'], [2, 'a'], [2, 'b'], [2, 'c'], [2, 'd'], [3, 'a'], [3, 'b'], [3, 'c'], [3, 'd'], [4, 'a'], [4, '
[5, 5, 6, 4, 13]
keyboard_arrow_down Conclusion
List comprehensions are a powerful and concise way to create lists in Python. They are syntactically compact and can replace more verbose
looping constructs. Understanding the syntax of list comprehensions will help you write cleaner and more efficient Python code.
https://colab.research.google.com/drive/11Faup-xQ_1t0LtzlCQBbYyWPZnOWzUKW#printMode=true 4/4