|
| 1 | +# List basic operations and methods in Python |
| 2 | + |
| 3 | +students = ['Ali', 'Haider', 'Husnain', 'Rai'] |
| 4 | + |
| 5 | +print(students[0]) # Access a specific index |
| 6 | +print(students) # Print the whole list |
| 7 | +print(len(students)) # Find the length of the list |
| 8 | + |
| 9 | +# Slicing |
| 10 | +print(students[:2]) # Show elements from index 0 to 1 (2 not included) |
| 11 | +print(students[2:]) # Show elements from index 2 to the end |
| 12 | +print(students[:]) # Show all elements |
| 13 | + |
| 14 | +# Replacing part of the list |
| 15 | +students[1:2] = ['Rai Muhammad Haider', 'Ali', 'Haider', 'Husnain', 'Rai'] |
| 16 | +print(len(students)) |
| 17 | +print(students) |
| 18 | + |
| 19 | +# Iterating over list with custom end character |
| 20 | +# for name in students: |
| 21 | +# print(name, end='-') |
| 22 | + |
| 23 | +students.append('Orange') # Add value at the end |
| 24 | +students.pop() # Remove the last value |
| 25 | +students.remove('Rai Muhammad Haider') # Remove a specific value by name |
| 26 | +students.insert(0, 'Inserted value') # Insert value at a specific index |
| 27 | + |
| 28 | +students.sort() # Sort list alphabetically or numerically |
| 29 | +print(students) |
| 30 | + |
| 31 | +only_reference = students # Creates a reference (both point to the same list) |
| 32 | +New_students = students.copy() # Creates a separate copy in memory |
| 33 | + |
| 34 | +New_students.insert(0, 'New Student') # Insert into copied list |
| 35 | + |
| 36 | +print(New_students) # Both lists are now different |
| 37 | +print(students) |
| 38 | + |
| 39 | +# Membership test |
| 40 | +if 'Ali' in students: |
| 41 | + print('Yes, Ali is in the list.') |
| 42 | + |
| 43 | +# List comprehension for square numbers |
| 44 | +square_number = [x**2 for x in range(10)] |
| 45 | +print(square_number) |
| 46 | + |
| 47 | +# List comprehension for cube numbers |
| 48 | +cube = [x**3 for x in range(5)] |
| 49 | +print(cube) |
| 50 | + |
| 51 | +# List extension and sorting |
| 52 | +list1 = [1, 9, 0, 4, 5] |
| 53 | +list2 = ['apple', 'orange', 'banana'] |
| 54 | + |
| 55 | +# list1.extend(list2) # Combine list1 and list2 (uncomment to use) |
| 56 | +# print(list1) |
| 57 | + |
| 58 | +print(list2) |
| 59 | + |
| 60 | +list2.sort() # Sort alphabetically (a to z) |
| 61 | +print(list2) |
| 62 | + |
| 63 | +list1.sort(reverse=True) # Sort in descending order |
| 64 | +print(list1) |
| 65 | + |
| 66 | +list1.reverse() # Reverse the list elements |
| 67 | +print(list1) |
| 68 | + |
| 69 | +# Using enumerate to get index and value |
| 70 | +for index, value in enumerate(list1): |
| 71 | + print(index, value) |
0 commit comments