List data type Variable in Python

 List Variable in Python :

What is a list variable 

A list in python is a built in data structure that allows you to store multiple items in a single variable. It is one of the most commonly used data types in python. 

syntax : 

my_list=[item1, item2, item3, ....]

  •  Ordered : items have arrange a defined order what you like 
  • Mutable : You want to any change in elements do it  that is remove  or add that's like 
  • Allows duplicates : if you want duplicate elements in the list, list       can have the same elements in multiple items
  • can store any data type that is numbers, strings, booleans, or even other lists 
How to create a list :
create a list using square brackets [ ]

my_list=[]

my_list=[item1, item2, ..]  

like these place your list of elements in list data type 

example :

fruits = ["apple", "banana", "cherry"]
print(fruits)

# string having  double quotes because we use double quotes 
Output: 
['apple', 'banana', 'cherry']


Types of lists : 


1. Hard-coded: Use this method when you already know the values that will be in the list.

2. split(): Use this function when you want to create a list from string.

3. range(): Use the range function when you want to create a sequence of numbers.

  • example of hard cored list :

number_list=[1, 2, 3]
print(number_list)

Output :
[1, 2, 3]

  • split() in python :

the split method is used with strings, not with lists it splits a string into a list of substrings, based on a separator with comma or dot etc. 

syntax :

string.split()

example :
text = "pro in python"
result = text.split()
print(result)

Output :
['pro', 'in', 'python']

  • range() in Lists (Python):

The range() function is commonly used with lists to generate a sequence of numbers. It’s especially useful for loops and list creation.

Syntax:
range(stop)
range(start, stop)
range(start, stop, step)

Example 1: Convert range() to list
numbers = list(range(5))
print(numbers)
Output:
[0, 1, 2, 3, 4]

Example 2: Range with start and stop
numbers = list(range(2, 7))
print(numbers)
Output:
[2, 3, 4, 5, 6]

Example 3: Range with step
even_numbers = list(range(0, 11, 2))
print(even_numbers)
Output:
[0, 2, 4, 6, 8, 10]

Example 4: Using range() in a for loop
for i in range(3):
    print("Hello", i)
Output:
Hello 0
Hello 1
Hello 2



  • You have to must try in your python compiler use idle avoid online compilers to Errors

Post a Comment

0 Comments