Skip to content

Commit 0221ef2

Browse files
author
majid shahbaz
committed
Lists Advance implementation
1 parent 606d36f commit 0221ef2

File tree

3 files changed

+529
-3
lines changed

3 files changed

+529
-3
lines changed

src/datastructures/lists/README.md

Lines changed: 278 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,4 +129,281 @@ queue.popleft()
129129
print(queue)
130130
# [2,3,4,5]
131131
```
132-
---
132+
---
133+
134+
### Python Lists: Advance
135+
136+
### Table of Contents
137+
1. [Converting Collections to Lists](#converting-collections-to-lists)
138+
2. [Basic List Operations](#basic-list-operations)
139+
3. [List Indexing and Slicing](#list-indexing-and-slicing)
140+
4. [Creating Lists with Loops](#creating-lists-with-loops)
141+
5. [Iterating Through Lists](#iterating-through-lists)
142+
6. [2D Lists (Matrices)](#2d-lists-matrices)
143+
144+
---
145+
146+
### Converting Collections to Lists
147+
148+
Python allows you to convert various data types into lists using the `list()` function.
149+
150+
### From Tuple to List
151+
```python
152+
# Convert tuple to list
153+
from_tuple_to_list = list(("a", "b", "c"))
154+
print(from_tuple_to_list) # Output: ['a', 'b', 'c']
155+
```
156+
157+
### From Set to List
158+
```python
159+
# Convert set to list
160+
from_set_to_list = list({"a", "b", "c"})
161+
print(from_set_to_list) # Output: ['a', 'b', 'c'] (order may vary)
162+
```
163+
164+
### From String to List
165+
```python
166+
# Convert string to list (each character becomes an element)
167+
from_string_to_list = list("abc")
168+
print(from_string_to_list) # Output: ['a', 'b', 'c']
169+
```
170+
171+
---
172+
173+
### Basic List Operations
174+
175+
#### 1. Accessing Elements
176+
```python
177+
thisList = ["a", "b", "c", 1]
178+
print(f"Access Element => {thisList[0]}") # Output: Access Element => a
179+
```
180+
181+
#### 2. Negative Indexing
182+
Negative indexing allows you to access elements from the end of the list:
183+
- `-1` refers to the last item
184+
- `-2` refers to the second last item, etc.
185+
186+
```python
187+
print(f"Negative indexing -> element at -1 index => {thisList[-1]}")
188+
# Output: Negative indexing -> element at -1 index => 1
189+
```
190+
191+
---
192+
193+
### List Indexing and Slicing
194+
195+
#### Range of Indexes
196+
You can specify a range of indexes to get a subset of the list. The syntax is `list[start:end]` where `end` is exclusive.
197+
198+
```python
199+
thisList = ["a", "b", "c", 1]
200+
201+
# Get elements from index 0 to 1 (excludes index 2)
202+
print(f"Range [0:2] => {thisList[0:2]}") # Output: ['a', 'b']
203+
204+
# From start to index 2 (excludes index 3)
205+
print(f"Range [:3] => {thisList[:3]}") # Output: ['a', 'b', 'c']
206+
207+
# From index 2 to end
208+
print(f"Range [2:] => {thisList[2:]}") # Output: ['c', 1]
209+
```
210+
211+
#### Negative Range Indexing
212+
```python
213+
# Get elements using negative indexing
214+
print(f"Negative Range [-3:-2] => {thisList[-3:-2]}") # Output: ['b']
215+
```
216+
217+
---
218+
219+
### Creating Lists with Loops
220+
221+
#### Method 1: Traditional For Loop
222+
```python
223+
# Add numbers 0 to 5 to the list
224+
emp_list = []
225+
for i in range(6):
226+
emp_list.append(i)
227+
print(f"Items in list Method 1: => {emp_list}")
228+
# Output: Items in list Method 1: => [0, 1, 2, 3, 4, 5]
229+
```
230+
231+
#### Method 2: User Input with Loop
232+
```python
233+
# Example of taking user input (commented in original code)
234+
emp_list_two = []
235+
size_of = int(input("Enter the size of list: "))
236+
for i in range(size_of):
237+
emp_list_two.append(i)
238+
print(f"Items in list Method 2: => {emp_list_two}")
239+
```
240+
241+
#### Method 3: User Input for Elements
242+
```python
243+
# Example of taking elements from user (commented in original code)
244+
emp_list_three = []
245+
size_of = int(input("Enter the size of list: "))
246+
for _ in range(size_of):
247+
element = input("Enter the element: ")
248+
emp_list_three.append(element)
249+
print(f"Items in list Method 3: => {emp_list_three}")
250+
# Note: All elements are strings because input() returns strings
251+
```
252+
253+
#### Method 4: List Comprehension (Modern Approach)
254+
255+
**Basic List Comprehension:**
256+
```python
257+
empty_list_comp = [i for i in range(4)]
258+
print(f"Items in list comprehension 1: => {empty_list_comp}")
259+
# Output: Items in list comprehension 1: => [0, 1, 2, 3]
260+
```
261+
262+
**Advanced List Comprehension:**
263+
```python
264+
# Example with user input (commented in original code)
265+
size = int(input("Enter the size of the list: "))
266+
items = [input(f"Enter item {_+1}: ") for _ in range(size)]
267+
print(f"Items in list => {items}")
268+
```
269+
270+
---
271+
272+
### Iterating Through Lists
273+
274+
#### Using For Loop with Range
275+
```python
276+
thisList = ["apple", "banana", "cherry"]
277+
for i in range(len(thisList)):
278+
print(f"Printing using for loop => {thisList[i]}")
279+
280+
# Output:
281+
# Printing using for loop => apple
282+
# Printing using for loop => banana
283+
# Printing using for loop => cherry
284+
```
285+
286+
#### Using While Loop
287+
```python
288+
i = 0
289+
while i < len(thisList):
290+
print(f"Printing using while loop => {thisList[i]}")
291+
i += 1
292+
293+
# Output:
294+
# Printing using while loop => apple
295+
# Printing using while loop => banana
296+
# Printing using while loop => cherry
297+
```
298+
299+
#### Using List Comprehension for Printing
300+
```python
301+
[print(f"Printing using List comprehension loop => {thisList[i]}")
302+
for i in range(len(thisList))]
303+
304+
# Output:
305+
# Printing using List comprehension loop => apple
306+
# Printing using List comprehension loop => banana
307+
# Printing using List comprehension loop => cherry
308+
```
309+
310+
---
311+
312+
### 2D Lists (Matrices)
313+
314+
A 2D list is a list of lists, commonly used to represent tables or matrices. The structure follows `[Rows][Columns]` indexing.
315+
316+
#### Matrix Structure Visualization
317+
```
318+
matrix = [
319+
[1, 2, 3], # Row 0
320+
[4, 5, 6], # Row 1
321+
[7, 8, 9] # Row 2
322+
]
323+
324+
Visual representation:
325+
Column0 Column1 Column2
326+
Row0 → 1 2 3
327+
Row1 → 4 5 6
328+
Row2 → 7 8 9
329+
```
330+
331+
#### Accessing Matrix Elements
332+
333+
**Access Single Element:**
334+
```python
335+
matrix = [
336+
[1, 2, 3],
337+
[4, 5, 6],
338+
[7, 8, 9]
339+
]
340+
341+
print(f"Element at [0][0] => {matrix[0][0]}") # Output: 1
342+
```
343+
344+
**Access Entire Row:**
345+
```python
346+
print(f"First Row => {matrix[0][:]}") # Output: [1, 2, 3]
347+
```
348+
349+
**Access Column Elements:**
350+
```python
351+
# Print first column (index 0 from each row)
352+
for row in matrix:
353+
print(f"First Column element => {row[0]}")
354+
355+
# Output:
356+
# First Column element => 1
357+
# First Column element => 4
358+
# First Column element => 7
359+
```
360+
361+
#### Iterating Through All Matrix Elements
362+
```python
363+
# Print all elements
364+
for row in matrix:
365+
for element in row:
366+
print(f"Matrix element => {element}")
367+
368+
# Output:
369+
# Matrix element => 1
370+
# Matrix element => 2
371+
# Matrix element => 3
372+
# Matrix element => 4
373+
# Matrix element => 5
374+
# Matrix element => 6
375+
# Matrix element => 7
376+
# Matrix element => 8
377+
# Matrix element => 9
378+
```
379+
380+
#### Formatted Matrix Output
381+
```python
382+
# Create a nicely formatted matrix display
383+
print(" " * 8 + "Column0 Column1 Column2")
384+
385+
for row_index, row in enumerate(matrix):
386+
print(f"Row{row_index}", end=" ")
387+
for item in row:
388+
print(f"{item:<7}", end="") # Left-aligned with fixed width
389+
print() # New line after each row
390+
391+
# Output:
392+
# Column0 Column1 Column2
393+
# Row0 → 1 2 3
394+
# Row1 → 4 5 6
395+
# Row2 → 7 8 9
396+
```
397+
398+
---
399+
400+
### Key Takeaways
401+
402+
1. **List Conversion**: Use `list()` to convert tuples, sets, and strings to lists
403+
2. **Indexing**: Python uses 0-based indexing; negative indexing starts from the end
404+
3. **Slicing**: Use `[start:end]` syntax where `end` is exclusive
405+
4. **List Creation**: Multiple methods available, with list comprehension being the most Pythonic
406+
5. **2D Lists**: Think of them as lists containing other lists, accessed with `[row][column]` syntax
407+
6. **Iteration**: Multiple ways to loop through lists, choose based on your needs
408+
409+
This guide covers the fundamental operations and concepts for working with lists in Python, from basic operations to more complex 2D list manipulati

0 commit comments

Comments
 (0)