<jupyter_start><jupyter_text>3.2 List in pythonLists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it the most powerful tool in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects. **Lists are mutable**, and hence, they can be altered even after their creation.**List in Python are ordered and have a definite count**. The elements in a list are indexed according to a definite sequence and the indexing of a list is done with 0 being the first index. **Each element in the list has its definite place in the list, which allows duplicating of elements in the list, with each element having its own distinct place and credibility**.  3.2.1 Creating a ListLists in Python can be created by just placing the sequence inside the square brackets[]. Unlike Sets, a list doesn’t need a built-in function for the creation of a list.<jupyter_code># Python program to demonstrate
# Creation of List
 
# Creating a List
List = []
print("Blank List: ")
print(List)
 
# Creating a List of numbers
List = [10, 20, 14]
print("\nList of numbers: ")
print(List)
 
# Creating a List of strings and accessing
# using index
List = ["Geeks", "For", "Geeks"]
print("\nList Items: ")
print(f"fist item: List[0]")
print(f"Third item: List[2]")
 
# Creating a Multi-Dimensional List
# (By Nesting a list inside a List)
List = [['Geeks', 'For'] , ['Geeks']]
print("\nMulti-Dimensional List: ")
print(List)<jupyter_output>Blank List: 
[]

List of numbers: 
[10, 20, 14]

List Items: 
fist item: List[0]
Third item: List[2]

Multi-Dimensional List: 
[['Geeks', 'For'], ['Geeks']]<jupyter_text>Creating a list with multiple distinct or duplicate elementsA list may contain duplicate values with their distinct positions and hence, multiple distinct or duplicate values can be passed as a sequence at the time of list creation.<jupyter_code># Creating a List with
# the use of Numbers
# (Having duplicate values)
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("\nList with the use of Numbers: ")
print(List)
 
# Creating a List with
# mixed type of values
# (Having numbers and strings)
List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']
print("\nList with the use of Mixed Values: ")
print(List)
# get the length of a list
print(f"the length of the list: {len(List)}")<jupyter_output>the length of the list: 7<jupyter_text>3.2 Adding Elements to a List- append()- insert(item,)- extend(items)  3.2.1 Using appendUse **append() function, can only add one element at a time**. **Tuple and List** can be added to a List by using append.<jupyter_code># Creating a List
List = []
print("Initial blank List: ")
print(List)
 
# Addition of Elements
# in the List
List.append(1)
List.append(2)
List.append(4)
print("\nList after Addition of Three elements: ")
print(List)
 
# Adding elements to the List
# using Iterator
for i in range(1, 4):
    List.append(i)
print("\nList after Addition of elements from 1-3: ")
print(List)
 
# Adding Tuples to the List
List.append((5, 6))
print("\nList after Addition of a Tuple: ")
print(List)
 
# Addition of List to a List
List2 = ['For', 'Geeks']
List.append(List2)
print("\nList after Addition of a List: ")
print(List)<jupyter_output>Initial blank List: 
[]

List after Addition of Three elements: 
[1, 2, 4]

List after Addition of elements from 1-3: 
[1, 2, 4, 1, 2, 3]

List after Addition of a Tuple: 
[1, 2, 4, 1, 2, 3, (5, 6)]

List after Addition of a List: 
[1, 2, 4, 1, 2, 3, (5, 6), ['For', 'Geeks']]<jupyter_text>3.2.2 Using insert() method**append() method add elements at the end of the List**. For insert elements at the desired position, insert() method is used. The insert() method requires two arguments(position, value).<jupyter_code># Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)
 
# Addition of Element at
# specific Position
# (using Insert Method)
List.insert(3, 12)
List.insert(0, 'Geeks')
print("\nList after performing Insert Operation: ")
print(List)<jupyter_output>Initial List: 
[1, 2, 3, 4]

List after performing Insert Operation: 
['Geeks', 1, 2, 3, 12, 4]<jupyter_text>3.2.3 Using extend() method**Extend() is used to add multiple elements at the same time at the end of the list.**<jupyter_code># Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)
 
# Addition of multiple elements
# to the List at the end
# (using Extend Method)
List.extend([8, 'Geeks', 'Always'])
print("\nList after performing Extend Operation: ")
print(List)<jupyter_output>Initial List: 
[1, 2, 3, 4]

List after performing Extend Operation: 
[1, 2, 3, 4, 8, 'Geeks', 'Always']<jupyter_text>3.3 Accessing elements from the ListIn order to access the list items refer to the index number. Use the index operator [] to access an item in a list. The index must be an integer. **Nested lists are accessed using nested indexing.**<jupyter_code>List = ["Geeks", "For", "Geeks"]
 
# accessing a element from the
# list using index number
print("Accessing a element from the list")
print(List[0])
print(List[2])
 
# Creating a Multi-Dimensional List
# (By Nesting a list inside a List)
List = [['Geeks', 'For'] , ['Geeks']]
 
# accessing an element from the
# Multi-Dimensional List using
# index number
print("Accessing a element from a Multi-Dimensional list")
print(List[0][1])
print(List[1][0])<jupyter_output>Accessing a element from the list
Geeks
Geeks
Accessing a element from a Multi-Dimensional list
For
Geeks<jupyter_text>Negative indexing**In Python, negative sequence indexes represent positions from the end of the array**. Instead of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3]. Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc.Below figure shows how to use negative index:![List_element_indexing](https://raw.githubusercontent.com/pengfei99/Learning_Python/main/images/List_element_indexing.jpg)<jupyter_code>List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']
 
# accessing an element using
# negative indexing
print("Accessing element using negative indexing")
 
# print the last element of list
print(List[-1])
 
# print the third last element of list
print(List[-3])<jupyter_output>Accessing element using negative indexing
Geeks
For<jupyter_text>3.4 Removing Elements from the List- remove() 3.4.1 Using remove() method remove(val) function removes the first occurence of the element that matches val, an Error arises if the element doesn’t exist in the list. Remove() method only removes one element at a time, to remove a range of elements, the iterator is used. The remove() method removes the specified item.Note – Remove method in List will only remove the first occurrence of the searched element. If you have duplicate, you may want to use a<jupyter_code># Creating a List
List = [1, 2, 3, 4, 5,"toto","titi", 6,7, 8, 9, 10, 11, 12]
print("Initial List: ")
print(List)
 
# Removing elements from List
# using Remove() method
List.remove("toto")
List.remove(6)
print("\nList after Removal of two elements: ")
print(List)
 

#change the first element from 1 to 'a' 
List[0]='a'
print("List after changing value of first element: ")
print(List)

# below will raise an error, because 1 is no longer in the list
List.remove(1)
# create a new list
List = [1, 2, 3, 4, 5,"toto","titi", 6,7, 8, 9, 10, 11, 12]
# Removing elements from List using iterator method
for i in range(2, 5):
    List.remove(i)
print("\nList after Removing a range of elements: ")
print(List)<jupyter_output>List after Removing a range of elements: 
[1, 5, 'toto', 'titi', 6, 7, 8, 9, 10, 11, 12]<jupyter_text>3.4.2 Using pop() methodPop(position): position is the index of the element that we want to remove. It's optional, when empty, by default pop function removes only the last element of the set.<jupyter_code>List = [1,2,3,4,5]
 
# Removing element from the
# Set using the pop() method
List.pop()
print("\nList after popping an element: ")
print(List)
 
# Removing element at a
# specific location from the
# Set using the pop() method
List.pop(2)
print("\nList after popping a specific element: ")
print(List)<jupyter_output>List after popping an element: 
[1, 2, 3, 4]

List after popping a specific element: 
[1, 2, 4]<jupyter_text>3.5 Slicing of a ListIn Python List, to print a specific range of elements from the list, we use the **Slice operation**. Slice operation is performed on Lists with the use of a colon(:), it has the following general syntax: ```text[start : stop : steps] It means that slicing will start from index start will go up to index stop with inteval of steps.  Default value:- start is 0, - stop is last index of list- step is 1 They all can be negativeif start, stop are negative, it means we will count the index from the end of the listif step is negative, it means we will show elements of the list in reverse order.```For example:  - To print elements from beginning to a range use [: Index], - To print elements from end-use [:-Index], - To print elements from specific Index till the end use [Index:], - To print elements within a range, use [Start Index:End Index]- To print the whole List with the use of slicing operation, use [:]. - To print elements within a range with step value 2, use [Start Index:End Index:2]- Further, to print the whole List in reverse order, use [::-1].Note – To print elements of List from rear-end, use Negative Indexes.<jupyter_code># Creating a List
List = [0,1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
print("Initial List: ")
print(List)
 
# Print elements of a range
# using Slice operation
Sliced_List = List[3:8]
print("\nSlicing elements in a range 3-8: ")
print(Sliced_List)
 
# Print elements from a
# pre-defined point to end
Sliced_List = List[5:]
print("\nElements sliced from 5th "
      "element till the end: ")
print(Sliced_List)
 
# Printing elements from
# beginning till end
Sliced_List = List[:]
print("\nPrinting all elements using slice operation: ")
print(Sliced_List)
Sliced_List = List[::2]
print("\nPrinting all elements with step value 2: ")
print(Sliced_List)
Sliced_List = List[::3]
print("\nPrinting all elements with step value 3: ")
print(Sliced_List)<jupyter_output>Printing all elements with step value 3: 
[0, 3, 6, 9, 12]<jupyter_text>Negative index List slicing<jupyter_code># Creating a List
List = ['G','E','E','K','S','F','O','R','G','E','E','K','S']
print("Initial List: ")
print(List)
 
# Print elements from beginning to a pre-defined point using Slice
Sliced_List = List[:-6]
print("\nElements sliced till 6th element from last: ")
print(Sliced_List)
 
# Print elements of a range using negative index List slicing
# note the element at -1 (S) is not in the result
Sliced_List = List[-6:-1]
print("\nElements sliced from index -6 to -1")
print(Sliced_List)
 
# Printing elements in reverse using Slice operation
Sliced_List = List[::-1]
print("\nPrinting List in reverse: ")
print(Sliced_List)
Sliced_List = List[::-2]
print("\nPrinting all elements with step value -2: ")
print(Sliced_List)
Sliced_List = List[::-3]
print("\nPrinting all elements with step value -3: ")
print(Sliced_List)<jupyter_output>Printing all elements with step value -3: 
[12, 9, 6, 3, 0]<jupyter_text>3.6 List ComprehensionList comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc.A list comprehension generally consists of these parts : 1. Output expression, 2. Input sequence, 3. A variable representing a member of the input sequence and 4. An optional predicate part. ```textnewList = [ output_expression(element) for element in oldList if condition ] In this example oldList is the input sequence,  if condition is the optional predicate```<jupyter_code># below list contains square of all odd numbers from range 1 to 10
odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1]
print (odd_square)
# for understanding, above generation is same as,
odd_square = []
 
for x in range(1, 11):
    if x % 2 == 1:
        odd_square.append(x**2)
 
print (odd_square)<jupyter_output>[1, 9, 25, 49, 81]<jupyter_text>We can have iteration inside another iteration for looping through the input sequence<jupyter_code># below list contains prime and non-prime in range 1 to 50 
noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)] 

primes = [x for x in range(2, 50) if x not in noprimes] 
print (primes) 
   

# list for lowering the characters 
print ([x.lower() for x in ["A","B","C"]] )
   
# list which extracts number 
string = "my phone number is : 11122 !!"
   
print("\nExtracted digits") 
numbers = [x for x in string if x.isdigit()] 
print (numbers) 
   

# A list of list for multiplication table 
a = 5
table = [[a, b, a * b] for b in range(1, 11)] 
   
print("\nMultiplication Table") 
print(table)<jupyter_output>Multiplication Table
[[5, 1, 5], [5, 2, 10], [5, 3, 15], [5, 4, 20], [5, 5, 25], [5, 6, 30], [5, 7, 35], [5, 8, 40], [5, 9, 45], [5, 10, 50]]
{'fraction_non_alphanumeric': 0.11383739712329821, 'fraction_numerical': 0.027305591877547882, 'mean_word_length': 4.667829119442023, 'pattern_counts': {'":': 0, '<': 40, '<?xml version=': 0, '>': 40, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '13', 'dir': 'jupyter-structured-clean-dedup', 'id': '413872', 'license': 'Apache-2.0', 'n_tokens_mistral': 4434, 'n_tokens_neox': 4084, 'n_words': 1814, 'path': 'geeks_for_geeks/Lesson03_Data_types/02.List.ipynb', 'repo_name': 'pengfei99/Learning_Python', 'size': '13001'}